简体   繁体   中英

C# static class: should I pass the object to the constructor?

I have a static class (called Utils) with a few utility methods not associated with any particular object. Most of those methods however take a reference to the same object.

public static string Method1(Context context)
{......}

public static string Method2(Context context, Etc etc)
{......}

public static string Method3(Context context)
{......}

This (context) object is created in the main class of the system. But these static methods are used in different parts of the system at later events. Should I create a static constructor in the Utils class and initialize the context object from the main class? Or should I let each of the class that calls these static methods pass the context object since they already have a reference to it? What are the pros and cons of each approach?

Edit: By the way, if anyone is curious, this is a Xamarin.Android project.

Most of those methods however take a reference to the same object.

This is usually a very strong indication that either (1) the methods may be out of place in the utility class, or (2) the utility class should not be static.

Should I create a static constructor in the Utils class and initialize the context object from the main class?

This may not be possible when the context is created elsewhere, because your utility class might get initialized at some unexpected time.

Or should I let each of the class that calls these static methods pass the context object since they already have a reference to it?

If you decide to do so, perhaps it's a good idea to move the method into Context , or if it is not possible, make your utility methods into extension methods:

public static string Method1(this Context context) {
    ...
}

This would let you save on typing, because you wouldn't have to spell out the name of your utility class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM