Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# What is the different between static class and non-static (I am talking about the class itself not the field) [duplicate]

Tags:

c#

class

static

The syntax maybe wrong

public static class Storage
{
    public static string filePath { get; set; }
}

And

public class Storage
{
    private void Storage () {};
    public static string filePath { get; set; }
}

I got this from an example on the internet. what is the use of the second one?

like image 270
Athiwat Chunlakhan Avatar asked Aug 14 '09 06:08

Athiwat Chunlakhan


2 Answers

If you look at the IL code, the static class will be abstract and sealed which gives two important qualities:

  • You cannot create instances from it
  • It cannot be inherited

A consequence of the first point is that a static class cannot contain non-static members. There may be many uses of static members in a non-static class. One common use is to have a class factory:

public class SomeClass
{
    public int SomeInt { get; set; }

    public static SomeClass Create(int defaultValue)
    {
        SomeClass result = new SomeClass();
        result.SomeInt = defaultValue;
        return result;
    }
}
like image 91
Fredrik Mörk Avatar answered Oct 18 '22 18:10

Fredrik Mörk


Here is the official/MSDN hot-spot to learn about static classes

The main features of a static class are:
* They only contain static members.
* They cannot be instantiated.
* They are sealed.
* They cannot contain Instance Constructors

Basically a static class is identical to a 'normal'/non-static class which has only static methods and a private ctor. Marking it as static helps clarify intent and helps the compiler do some compile-time checks to disallow certain things e.g. disallow instantiation.

Real-world uses I can think of: Use it to house or as a way to organize

  • utility methods (methods not associated with any instance of a type) e.g. Math for Min and Max methods
  • extension methods e.g. StopWatchExtensions for a Reset method on a StopWatch
like image 41
Gishu Avatar answered Oct 18 '22 19:10

Gishu