user3328870
user3328870

Reputation: 361

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; }
    }
}

Upvotes: 0

Views: 91

Answers (4)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236278

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.

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

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.

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59272

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.

Upvotes: 2

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

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;}

}

Upvotes: 2

Related Questions