简体   繁体   中英

In case i have class with only one static variable - should i declare this class as static?

This is my class how hold my last visited Path:

public class LastPath
{
    private static string _lastPath;

    public static string lastPath
    {
        get { return _lastPath; }
        set { _lastPath = value; }
    }
}

I would say you to do this:

public static class LastPath
{
    public static string lastPath
    {
       get;set;
    }
}

You should declare it as static as static classes cannot be instantiated, while non static classes can be instantiated, which is not needed.

make the class static and make a public property as static and you are done, like this:

public static class LastPath
{

    public static string lastPath { get;set;}

}

If all members of a class is static and your class is not meant to instantiated it should be static .

In this case your class satisfies the above rule or guideline so marking it as static will make sense because you don't have any instance member.

LastPath path = new LastPath();
path.????//  Nothing to access, so prevent instantiation by marking class static.

Being said that If you have only one field in your class and no methods I'd argue that you probably don't need a class at all, just refactor it to some other class where it would make sense.

First - it looks odd to me to create class for holding single variable. Consider to use simple string variable lastVisitedPath instead. If you use this variable in single class, then make it field of that class.

Second - naming is not very readable. Here is how getting last path looks like: LastPath.lastPath . You see this useless duplication? Also keep in mind, that due to Microsoft naming guidelines public members should have Pascal Case names. Consider to create class with descriptive name like GlobalValues or Cache which reflects its purpose:

public static class GlobalValues // holds values which are globally accessible
{
   public static string LastVisitedPath;
   // other global values
}

So that usage will look like GlobalValues.LastVisitedPath or Cache.LastVisitedPath . Of course, if these classes don't supposed to be instantiated, they should be static.

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