C# inheritence and static classes - c#

Why can't a static class be inherited into a normal class?

If B inherits from (is a subclass of) A, that means an instance of B can be stored in a variable of type A, and its virtual methods will call those of class B.
For static classes, you don't have the concept of an instance of the class, so there's no way to inherit. You might have better luck with a static (singleton) reference to a regular class.

From Static Classes and Static Class Members (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 contain a static constructor.

As an alternative to inheriting from a static class, you can assign extension methods to interfaces.

You can not inherit a static class - The reason is simple. Static classes are marked as abstract and sealed in compiled IL which can be neither instantiated nor inherited.

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)
Source:
Why can't I inherit static classes?

Related

Inheritance isn't working properly for generic abstract object factories

I have the following basic object factory for when I want some members of a class hierarchy to have special construction code and any other members to have generic constructors.
My problem here is that TileFactory doesn't have the method GetInstance--my program won't compile if I try to call TileFactory.GetInstance(). Any advice?
public static class ObjectFactory<K>
{
public static T GetInstance<T>() where T : K
{
T obj = (T)Activator.CreateInstance(typeof(T));
return obj;
}
//snip
}
}
//snip
public static class TileFactory : ObjectFactory<Tile>
{
}
Why can't I inherit static classes?
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.
http://www.dofactory.com/Patterns/PatternSingleton.aspx
There is no inheritance for static things. A workaround is to use singletons.

Query regarding static class in c#

Hi all I just wanted to know whether a static class which inherits another class, can have access to the parent classe's non static members or not?
Please help. Thanks in advance.
A static class cannot inherit or implement any class or interface.
The point of inheriting or implementing a class or interface is to allow instances of your class to be used as the base type.
Since static classes cannot have instances, there's no point.
How should that work? A static class cannot be instantiated and therefor it will never have access to any non static members.
A static class is basically the same
as a non-static class, but there is
one difference: a static class cannot
be instantiated. In other words, you
cannot use the new keyword to create a
variable of the class type
You can view more information about static classes.
static class cannot inherited .
I think you can go with the same concept with SingleTon class and you can inherit the same.
A static class can't inherit from any classes or implement any interfaces.
A static class does implicitly inherit from Object, though. But since it's (also implicitly) abstract you can never have any instances of it, and so can never call any instance methods in Object. Also, it's (implicitly) sealed, and as such cannot have subclasses that would be instantiatable. As a corollary to these characteristics, it can't be used to type any variables, fields or parameters; and it can't be used as a type parameter (if these were possible, null would be the only valid value for such references).
Given all this, a static class does not look like a class at all, and I think would be better represented as a module.

What's the difference between an abstract class and a static one?

Neither is instantiable. What are the differences, and in what situations might you use one or the other?
static indicates the class can only have static members and you cannot create an instance of it. This is used for stateless functionality (for example a type that just defines extension methods, or utility methods). You can also declare a member static on a non-static class. This allows you to attach functionality to a type without having to instantiate it.
Here's more detail on using static members and classes.
abstracts define the basic structure and functionality shared by all derivative types, but cannot be used by themselves. Think of them as, I suppose, a blue print and a contract. This is a core concept for OOP.
Here's more detail on using abstracts.
Here is a short summary:
A static class can only contain static members (it is just a container for methods that do not logically belong to an instance of any standard class)
An abstract class can contain all usual kinds of members (static, abstract and also instance)
The key difference is that you can inherit from an abstract class, but you cannot inherit from a static class. Technically speaking, the .NET runtime doesn't have any notion of static classes, so the C# compiler compiles them as classes that are both abstract and sealed (meaning that you cannot inherit from them).
So, static classes are abstract classes that are also sealed (although this is not the usual way to look at the problem if you are C# programmer) and contain only static members (which is enforced by the C# compiler).
An abstract class is intended to be used as a base of a class inheritance hierarchy. A static class cannot be the base of a class inheritance hierarchy.
A static class is intended for singleton state or stateless functionality. An abstract class is not suitable for singleton functionality, because, even though it may contain static methods and fields as a static class does, it cannot forbid inheritance, so the singleton use may be defeated by subclasses. Or, at the very least, it would be confusing to other programmers, because its definition would communicate an intent that is different from its actual intended use.
The superficial similarity between abstract and static classes is only in the fact that neither may be instantiated. Beyond that, they are completely different animals with completely different use cases.
The CLR has no notion of static classes, it is specific to C#. The compiler implements it by slick use of CLR attributes for a class: it declares it abstract and sealed. That prevents any language from instantiating such a class. This is what it looks like when you run Ildasm:
.class public abstract auto ansi sealed beforefieldinit ConsoleApplication1.Test
extends [mscorlib]System.Object
{
}
Making it sealed is very much the point of a static class, it is used as a container for static methods and fields. Which makes them act like global variables and functions like you have in languages like C or Pascal.
An abstract class is very much the opposite, it is designed to be derived from. A abstract class that has all of its member abstract acts like an interface. C# has a keyword for that, making static class and interface the exact opposites.
Abstract classes get instantiated indirectly via derived classes. They provide common behaviour and instance state, but signal that more is required and must be provided by derived concrete classes. For example, Transform might be an abstract class: it declares a common Apply(Shape) method, but no implementation of that method. Concrete derived classes like Rotation or Translation will implement that method, and those classes can be instantiated.
Static classes cannot be instantiated, and any state is at the class level rather than the instance level. They are typically used to define utility methods where there is no state associated with the methods. Transform couldn't be a static class, because the concrete derived classes need per-instance state (e.g. Rotation needs a per-instance Angle, because different Rotation transforms could be by different angles).
Abstract classes are intended to be used as base classes; they cannot have direct instances. Instead, you have to derive subclasses, which provide the what was (usually intentionally) left out in the abstract base class.
Example: consider you have a complex application, where users may log-in to. Various authentication mechanisms should be usable, say, LDAP, NTLM, you name it. One way to model a "user" or "principal" in such a context would be to collect, what is common across all those mechanisms, into an abstract base class, and leave "gaps" (abstract methods) where the actual implementations come into play:
abstract class Authenticator {
protected Dictionary<string,User> userCache;
...
public User LoadUser(string name) {
User user;
if( userCache.TryGet(name, out user) ) return user;
else {
user = LoadFromStore(name);
userCache.Add(name, user);
return user;
}
}
protected abstract User LoadFromStore(string name);
}
Here, caching of users is a common concern, modelled in the base case, whereas the actual retreival is left for a subclass to provide.
Static class are a different matter alltogether. They are essentially a place to keep your utility functions:
static class StrUtil {
public static string TrimWhitespace(string str) {
...
}
}
Think of them as some kind of special namespace, which can only contain static members. Basically, a place to put functions.
Abstract Class (Base class):
Enables other classes to inherit from this class (one class acquires the properties (methods and fields) of another) , but forbids to instantiate i.e we cannot have objects of this class.
http://csharp.net-tutorials.com/classes/abstract-classes
Static Class:
This class cannot be instantiated. Also this class cannot be inherited. To access methods of this class, you can directly use classname.method.
https://social.technet.microsoft.com/wiki/contents/articles/21028.difference-between-static-class-sealed-class-and-abstract-class-in-c.aspx
Abstract class main purpose is to define one or more abstract method(s).
Any class extending Abstract class will implement the abstract method or else its also need to be declared as "Abstract".
But, its also possible to declare a class as "Abstract" without implementing any abstract method(s) in it. See the sample below.
public abstract class AbstractTest {
public void abcd(){}
public static void main(String[] args) {
System.out.print("hi...");
}
}
Only inner class can be declared as "Static", see the code below.
Upper/encapsulating class can't be declared as "Static".
It can be accessed by using Upper/encapsulating class variable.Static-inner-classname i.e same as any static method invocation using class name.
public class StaticTest {
public static void main(String ag[]){
System.out.println("hello...1");
StaticTest.StaticTest2.meth2();
}
public static class StaticTest2 {
public static void meth2(){
System.out.print("hello...2");
}
}
}
Main difference between the two is extensibility.
CLR marks all 'static' classes as 'abstract & sealed' behind the scene (i.e., they cannot be inherited hence cannot be extended) and .NET Framework CLR loads them automatically when containing program or namespace is loaded. This gives performance gain on runtime.
Philosophy behind 'abstract' classes is capitalizing all common features of all extended classes in one place.
Hope it helps.

In C#, what is the purpose of marking a class static?

In C#, what is the purpose of marking a class static?
If I have a class that has only static methods, I can mark the class static or not. Why would I want to mark the class static? Would I ever NOT want to mark a class static, if all the methods are static, and if I plan to never add a non-static method?
I looked around and saw some similar questions, but none that were just like this.
Marking a class as static is a declarative statement that you only intend for this type to have static and const members. This is enforced by the compiler and prevents you from accidentally adding an instance method to the type.
Other advantages
Extension methods can only be defined in static classes
Prevents users from creating an instance of the class
Prevents use of the type as a generic argument (thanks Eric!)
Marking a class as static gets you two important things.
Compiler verification that you only put static members in a class.
An obvious statement to readers of your code that this class is only a container for static members.
The feature was invented in response to a bug in NDP v1.0, where a un-callable non-static member was included in the System.Environment class.
If you would like to write extension methods, you have to use a static class. Otherwise it is to show the class will never have any instance data.
It is a convention specific to the C# language, the CLR has no notion of static classes. It ensures that you cannot accidentally add an instance member in the class, cannot inherit the class and client code cannot accidentally create an instance of the class. The underlying TypeAttributes for the class are Abstract and Sealed. Abstract ensures that the new operator can't work, Sealed ensures that you can't inherit from the class.
Also by convention, extension methods must be static members of a static class. VB.NET does it differently, it requires the [Extension] attribute.
Using static classes in your code is not necessary, but it is useful. Their contract is very descriptive, it makes your code easier to understand. But be careful not to use them as a vehicle to write procedural code instead of OOP code.
You mark a class static if you want to force it to contain only static methods, a typical helper class. If you put an instance method the compiler will complain - this is good. In version 1 of the .NET framework there was a class, don't remember which one, that was meant to ship with only static methods. Accidentally one of those methods did not get the static modifier. Because this feature did not exist at the time the bug was spotted very late, after shipping. They did make the constructor private and as such the method could not be used.

Can we have a private constructor in a static class?

I have a doubt that a static class can contain a private constructor.
Static classes cannot have instance constructors
http://msdn.microsoft.com/en-us/library/79b3xss3.aspx
The following list provides the main features of a static class:
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.
A static class cannot have any instance constructor ( see CS0710 ), whether it be public, private, protected or internal.
See the following article for more info.
Static Classes and Static Class Members (C# Programming Guide)
What would this constructor do? The class is static, so it is never instantiated. You can have a static constructor on a non-static class to initialize static fields, but on a static class, the only constructor that makes sense is the static constructor, and that gets called be the CLR.
Addition: Jon Skeet posted an article about the timing of the initialization of the static class (normally it's initialized on first use, but sometimes you want to initialize it when the program starts) and a possible change in .net 4.
Your doubt is correct.
A static class can only have a static constructor and public/private does not apply since your code can never call this constructor (the CLR does).
So you may not use a access modifier (public/private/...) on a static constructor.
rule is static classes cannot have instance constructors

Categories