Question

I have a static class called A:

public static class A
{
}

And another class called B, which is not static:

public class B
{
}

After that, I declared the non-static class B as static:

public class c
{
    // declare a non static class (B) as static
    public static B b = new B();
}

What is the difference between A (static class) and b (non-static class declared as a static class)?

Was it helpful?

Solution

In a static class you can only declare static members (methods, fields, properties). In a non-static class, you can declare both static members and instance (non-static) members.

Also, you cannot derive a class from a static class, or instantate it, or use it as a type argument.


When you define a static member:

public static B b = new B();

...then you are saying that this field b of type B belongs only to the type you declared it in. Non-static fields belong to an instance of the type.


For example, if you have:

class MyClass
{
    public static string myStaticString = "";

    public string myInstanceString = "";
}

Then if you change the myInstanceString, its value will only change for that particular instance:

MyClass myInstance1 = new MyClass();
MyClass myInstance2 = new MyClass();
myInstance1.myInstanceString = "1";
myInstance2.myInstanceString = "2";
Console.WriteLine(myInstance1.myInstanceString);  // Prints: 1
Console.WriteLine(myInstance2.myInstanceString);  // Prints: 2

But if you change the myStaticString, its value will change for everyone that uses the type:

MyClass.myStaticString = "1";
MyClass.myStaticString = "2";
Console.WriteLine(MyClass.myStaticString);        // Prints: 2

And that is completely unrelated to whether string (or B in your example) was declared as static.

OTHER TIPS

The difference is the difference between the static variable and the static class. b is a static variable of non static type B, However A is a static class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top