What is a "static" class? - c#

In C# what is the difference between:
public static class ClassName {}
And:
public class ClassName {}

Firstly, a comment on an answer asked about what "static" means. In C# terms, "static" means "relating to the type itself, rather than an instance of the type." You access a static member (from another type) using the type name instead of a reference or a value. For example:
// Static method, so called using type name
Guid someGuid = Guid.NewGuid();
// Instance method, called on a value
string asString = someGuid.ToString();
Now, static classes...
Static classes are usually used as "utility" classes. The canonical example is probably System.Math. It doesn't make sense to create an instance of math - it just "is". A few rules (both "can" and "can't"):
Static classes always derive from object. You can't specify a different base type, or make the static class implement an interface.
Static classes can't have any instance members - all variables, methods etc must be static.
Static classes can't declare any instance constructors and the compiler doesn't create a parameterless constructor by default. (Before static classes came in C# 2.0, people would often create an abstract class with a private constructor, which prevented instantiation. No need here.)
Static classes are implicitly abstract (i.e. they're compiled to IL which describes an abstract class) but you can't add the abstract modifier yourself.
Static classes are implicitly sealed (i.e. they're compiled to IL which describes an sealed class) but you can't add the sealed modifier yourself.
Static classes may be generic.
Static classes may be nested, in either non-static or static classes.
Static classes may have nested types, either non-static or static.
Only static, top-level non-generic classes can contain extension methods (C# 3.0).

A static class cannot be instantiated, and can contain only static members. Hence, the calls for a static class are as: MyStaticClass.MyMethod(...) or MyStaticClass.MyConstant.
A non static class can be instantiated and may contain non-static members (instance constructors, destructor, indexers). A non-static member of a non-static class is callable only through an object:
MyNonStaticClass x = new MyNonStaticClass(...);
x.MyNonStaticMethod(...);

public static class ClassName {}
A static class is just like a global variable: you can use it anywhere in your code without instantiating them.
For example: ClassName. After the dot operator, you can use any property or function of it.
public class ClassName {}
But if you have non-static class then you need to create an instance of this class.
For example:
ClassName classNameObject = new ClassName();

A static class also can not be inherited from, whereas a non-static class with static members can be inherited from.

All methods/properties in a static class must be static, whereas a 'normal' class can contain a mix of instance and static methods.

You can't instantiate (create objects of) a static class. And it can only contain static members.
Example: System.Math

Static class can contain static members only.
Static member can be used without instantiating a class first.

Static classes and members are used to create data and methods that can be accessed without creating an instance (using the new keyword, they cannot have a constructor) of the class.
Static classes can be declared when there is no dependence on the its own object identity, so a static class must contain only static members.
This classes are loaded by the CLR when the program or namespace containing the class is loaded.
They are also sealed, cannot be inherited from.

http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html - very good article on this. This is for Java. But i think concept should should same in C# too.

Static variable in c
a variable local to a class as auto variables
but static variable do not disappear as function is no longer active.Their values persist.If control comes back,static variables have same value
static function in c
functions that are not visible to functions in other files.
*static data members in cpp *
data members can be variables or functions in cpp
static applies to both data members
the class itself can be static
"There is only one copy of static data memberss shared by all objects in that class"
static data members can access only static data members
static class
this class cannot instantiate objects

Most importantly, "A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides." - From Microsoft

Related

How does the CLR handles static classes?

Can anyone explain how the CLR handles Static classes? Does the CLR create one singleton instance for handling static classes internally? If not, why do we have a static constructor in C#? (Per my understanding, we use constructors only for instantiating the class)
First of all there is no static class in CLR. CLR doesn't know anything about static class.
It is the feature of C#.
Static classes are compiled into abstract as well as sealed class. Making it abstract prevent instantiation of it and sealed prevents inheritance.
Static classes are no special, it is just a simple class with all members static.
Is, CLR internally creates one singleton instance for handling static
classes?
No, it is abstract and can't be instantiated.
If not why we have an static constructor in C#?
Static constructor will be called when type is first referenced or instantiated. It is used to initialize the static members of the class.
When is a static constructor called in C#?
The static constructor is called when the type is first referenced. It doesn't have to be a static class to have a static constructor.
The CLR doesn't create a singleton instance of a static class. It does keep the static variables in memory though after they are initialized.

what are the main differences between a Java/C# static class?

In C# a static class is a class that, in addition to not supporting inheritance, can have any kind of type member a "normal" class can have except instance members.
Not so sure how static classes work in java, but based on the limited amount of java code I have seen, it's clear to me that they don't work quite the same way.
Can someone please enumerate the differences?
Static classes in Java are one of three kinds of nested classes provided by the language (the other two being non-static nested classes and function-scoped classes).
Static classes of Java behave the same way that nested classes of C#: they have access to static members of the enclosing class, but cannot access instance members without an additional reference to the enclosing object. In contrast, non-static nested functions can access instance variables, but you need an enclosing instance in order to be instantiated.
in C#
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
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
in Java :
Only nested classes can be static.
can have static members in classes
In Java, you cannot have the outer most class as static. Only inner classes can be declared with the static modifier. Doing so prevents that inner class from having access to instance members of the outer class.
In C#, you can define the outer class with the static modifier, which makes it impossible to create instance variables of that class. These serve two different purposes. To create a similar effect in Java, you can define private no-args constructor. The singleton pattern implementation does so. Also in Java, can also create a class with all its members defined static, but that doesn't prevent creation of new instances.

What's the difference between a static struct method and a static class method?

I recently discovered that structs in C# can have methods.
Quite accidentally, I found myself to have been using the static method of an empty struct in my code, rather than the static method of a static class that I thought I was working with!
e.g.
public struct Foo
{
public static void Bar(Param param)
{
...
}
}
It's not really being used as a struct at this point, as it has no properties at all!
Is this very different from using a static method of a class (static or otherwise)? Are there any reasons to prefer one over the other? (My gut tells me that using the static struct method is, at minimum, less intuitive)
No, static members belong to the type and not to instances of the type. There is no difference (neither with respect to performance nor semantics) between declaring static class members and static struct members.
It is important to note that if a type's only function is to contain static members, you should use a static class instead. With structs, there is an implicit and unchangeable public, no-argument constructor. If the type will not have any instance methods, the ability to create instances should be removed. Declaring a class static is the same as declaring it abstract sealed, so developers will not be able to accidentally create instances that have no purpose.
The behavior is no different. C# bastardized structs by hugely increasing the intersection of struct and class features. Personally I would just use a class because it seems more correct to me (certainly more in line with the conventions in most languages).

what is difference making full class static and making functions of the class as static

Hello All:
what is difference making full class static and making functions of the class as static?
I mean are there any performance issues?
The feature of static classes was only introduced in C# 2. The CLR doesn't really have such a concept. A static class in C#:
Has no constructors, not even a default parameterless one
Is sealed: it can't be subclassed
Is abstract: you can't create instances of it (which also follows from there being no constructors)
Can only contain static members
Can't be used as a parameter or variable type or a generic type argument etc.
Can't specify any base type other than object
There's no performance difference between using static members of a "normal" class and using ones in a static class. It's primarily a way of stating the intention that there should never be any instances of this class, without having to provide a private and never-called constructor, and forcing the compiler to check that you're not trying to use it as a normal class.
Note that extension methods (introduced in C# 3) can only be declared in a top-level, non-generic static class.
It has two implications:
All methods of the class must also be static.
You can't make an instance of that class other places in your code.

Why can't I inherit static classes?

I have several classes that do not really need any state. From the organizational point of view, I would like to put them into hierarchy.
But it seems I can't declare inheritance for static classes.
Something like that:
public static class Base
{
}
public static class Inherited : Base
{
}
will not work.
Why have the designers of the language closed that possibility?
Citation from here:
This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.
There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.
(Mads Torgersen, C# Language PM)
Other opinions from channel9
Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...
Static methods are only held once in memory. There is no virtual table etc. that is created for them.
If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?
(littleguru)
And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.
The main reason that you cannot inherit a static class is that they are abstract and sealed (this also prevents any instance of them from being created).
So this:
static class Foo { }
compiles to this IL:
.class private abstract auto ansi sealed beforefieldinit Foo
extends [mscorlib]System.Object
{
}
Think about it this way: you access static members via type name, like this:
MyStaticType.MyStaticMember();
Were you to inherit from that class, you would have to access it via the new type name:
MyNewType.MyStaticMember();
Thus, the new item bears no relationships to the original when used in code. There would be no way to take advantage of any inheritance relationship for things like polymorphism.
Perhaps you're thinking you just want to extend some of the items in the original class. In that case, there's nothing preventing you from just using a member of the original in an entirely new type.
Perhaps you want to add methods to an existing static type. You can do that already via extension methods.
Perhaps you want to be able to pass a static Type to a function at runtime and call a method on that type, without knowing exactly what the method does. In that case, you can use an Interface.
So, in the end you don't really gain anything from inheriting static classes.
Hmmm... would it be much different if you just had non-static classes filled with static methods..?
What you want to achieve by using class hierarchy can be achieved merely through namespacing. So languages that support namespapces ( like C#) will have no use of implementing class hierarchy of static classes. Since you can not instantiate any of the classes, all you need is a hierarchical organization of class definitions which you can obtain through the use of namespaces
You can use composition instead... this will allow you to access class objects from the static type. But still cant implements interfaces or abstract classes
Although you can access "inherited" static members through the inherited classes name, static members are not really inherited. This is in part why they can't be virtual or abstract and can't be overridden. In your example, if you declared a Base.Method(), the compiler will map a call to Inherited.Method() back to Base.Method() anyway. You might as well call Base.Method() explicitly. You can write a small test and see the result with Reflector.
So... if you can't inherit static members, and if static classes can contain only static members, what good would inheriting a static class do?
A workaround you can do is not use static classes but hide the constructor so the classes static members are the only thing accessible outside the class. The result is an inheritable "static" class essentially:
public class TestClass<T>
{
protected TestClass()
{ }
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public class TestClass : TestClass<double>
{
// Inherited classes will also need to have protected constructors to prevent people from creating instances of them.
protected TestClass()
{ }
}
TestClass.Add(3.0, 4.0)
TestClass<int>.Add(3, 4)
// Creating a class instance is not allowed because the constructors are inaccessible.
// new TestClass();
// new TestClass<int>();
Unfortunately because of the "by-design" language limitation we can't do:
public static class TestClass<T>
{
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public static class TestClass : TestClass<double>
{
}
You can do something that will look like static inheritance.
Here is the trick:
public abstract class StaticBase<TSuccessor>
where TSuccessor : StaticBase<TSuccessor>, new()
{
protected static readonly TSuccessor Instance = new TSuccessor();
}
Then you can do this:
public class Base : StaticBase<Base>
{
public Base()
{
}
public void MethodA()
{
}
}
public class Inherited : Base
{
private Inherited()
{
}
public new static void MethodA()
{
Instance.MethodA();
}
}
The Inherited class is not static itself, but we don't allow to create it. It actually has inherited static constructor which builds Base, and all properties and methods of Base available as static. Now the only thing left to do make static wrappers for each method and property you need to expose to your static context.
There are downsides like the need for manual creation of static wrapper methods and new keyword. But this approach helps support something that is really similar to static inheritance.
P.S.
We used this for creating compiled queries, and this actually can be replaced with ConcurrentDictionary, but a static read-only field with its thread safety was good enough.
My answer: poor design choice. ;-)
This is an interesting debate focused on syntax impact. The core of the argument, in my view, is that a design decision led to sealed static classes. A focus on transparency of the static class's names appearing at the top level instead of hiding ('confusing') behind child names? One can image a language implementation that could access the base or the child directly, confusing.
A pseudo example, assuming static inheritance was defined in some way.
public static class MyStaticBase
{
SomeType AttributeBase;
}
public static class MyStaticChild : MyStaticBase
{
SomeType AttributeChild;
}
would lead to:
// ...
DoSomethingTo(MyStaticBase.AttributeBase);
// ...
which could (would?) impact the same storage as
// ...
DoSomethingTo(MyStaticChild.AttributeBase);
// ...
Very confusing!
But wait! How would the compiler deal with MyStaticBase and MyStaticChild having the same signature defined in both? If the child overrides than my above example would NOT change the same storage, maybe? This leads to even more confusion.
I believe there is a strong informational space justification for limited static inheritance. More on the limits shortly. This pseudocode shows the value:
public static class MyStaticBase<T>
{
public static T Payload;
public static void Load(StorageSpecs);
public static void Save(StorageSpecs);
public static SomeType AttributeBase
public static SomeType MethodBase(){/*...*/};
}
Then you get:
public static class MyStaticChild : MyStaticBase<MyChildPlayloadType>
{
public static SomeType AttributeChild;
public static SomeType SomeChildMethod(){/*...*/};
// No need to create the PlayLoad, Load(), and Save().
// You, 'should' be prevented from creating them, more on this in a sec...
}
Usage looks like:
// ...
MyStaticChild.Load(FileNamePath);
MyStaticChild.Save(FileNamePath);
doSomeThing(MyStaticChild.Payload.Attribute);
doSomething(MyStaticChild.AttributeBase);
doSomeThing(MyStaticChild.AttributeChild);
// ...
The person creating the static child does not need to think about the serialization process as long as they understand any limitations that might be placed on the platform's or environment's serialization engine.
Statics (singletons and other forms of 'globals') often come up around configuration storage. Static inheritance would allow this sort of responsibility allocation to be cleanly represented in the syntax to match a hierarchy of configurations. Though, as I showed, there is plenty of potential for massive ambiguity if basic static inheritance concepts are implemented.
I believe the right design choice would be to allow static inheritance with specific limitations:
No override of anything. The child cannot replace the base
attributes, fields, or methods,... Overloading should be ok, as
long as there is a difference in signature allowing the compiler to
sort out child vs base.
Only allow generic static bases, you cannot inherit from a
non-generic static base.
You could still change the same store via a generic reference MyStaticBase<ChildPayload>.SomeBaseField. But you would be discouraged since the generic type would have to be specified. While the child reference would be cleaner: MyStaticChild.SomeBaseField.
I am not a compiler writer so I am not sure if I am missing something about the difficulties of implementing these limitations in a compiler. That said, I am a strong believer that there is an informational space need for limited static inheritance and the basic answer is that you can't because of a poor (or over simple) design choice.
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.
A class can be declared static, which indicates that it contains only static members. It is not possible to use the new keyword to create instances of a static class. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace that contains the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
Following are the main features of a static class:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors (C# Programming Guide).
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can have a static constructor. For more information, see Static Constructors (C# Programming Guide).
When we create a static class that contains only the static members and a private constructor.The only reason is that the static constructor prevent the class from being instantiated for that we can not inherit a static class .The only way to access the member of the static class by using the class name itself.Try to inherit a static class is not a good idea.
I run into the problem when trying to code an IComparer<T> implementation against a third-party library where T is an enum embedded in a class as in the following:
public class TheClass
{
public enum EnumOfInterest
{
}
}
But because the enum is defined within a third-party library class, I can't write the comparer because the following gives a "cannot extends list" error:
public class MyComparer : IComparer<TheClass.EnumOfInterest>
{
}
I'm not even extending a static class -- I'm just implementing a comparer of a enum defined in a class.

Categories

Resources