Inheritance C# Help

A generic type can implement a generic interface, The same is possible by deriving from a class. A generic class can be derived from a generic base class:

Img

The requirement is that the generic types of the interface must be repeated. or the type of the base class must be specified. as in this case:

Img

This way, the derived class can be a generic or non-generic class. For example. you can define an abstract generic base class that is implemented with a concrete type in the derived class. This allows you to do specialization for specific types:

Img

Static Members

Static members of generic classes require special attention. Static members of a generic class are only shared with one instantiation of the class. Let’s have a look at one example. The class StaticDemo<T> contains the static field x:

public class StaticDemo<T>
{
public static int x;

}

Because of using the class StaticDemo<T> both with a string type and an int type, two sets of static fields exist:

StaticDemo<string>.x = 4;
StaticDemo<int>.x = 5;
Console.WriteLine(StaticDemo<string>.x); // writes 4

Posted on October 29, 2015 in Generics

Share the Story

Back to Top
Share This