15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Generics features ❘ 117<br />

inheritance<br />

The LinkedList class created earlier implements the interface IEnumerable:<br />

public class LinkedList: IEnumerable<br />

{<br />

//...<br />

A generic type can implement a generic interface. The same is possible by deriving from a class. A generic<br />

class can be derived from a generic base class:<br />

public class Base<br />

{<br />

}<br />

public class Derived: Base<br />

{<br />

}<br />

The requirement is that the generic types of the interface must be repeated, or the type of the base class must<br />

be specified, as in this case:<br />

public class Base<br />

{<br />

}<br />

public class Derived: Base<br />

{<br />

}<br />

This way, the derived class can be a generic or non-generic class. For example, you can define an abstract<br />

generic base class that is implemented with a concrete type in the derived class. This allows you to do<br />

specialization for specific types:<br />

public abstract class Calc<br />

{<br />

public abstract T Add(T x, T y);<br />

public abstract T Sub(T x, T y);<br />

}<br />

public class IntCalc: Calc<br />

{<br />

public override int Add(int x, int y)<br />

{<br />

return x + y;<br />

}<br />

}<br />

public override int Sub(int x, int y)<br />

{<br />

return x — y;<br />

}<br />

static members<br />

Static members of generic classes require special attention. Static members of a generic class are only shared<br />

with one instantiation of the class. Let’s have a look at one example, where the class StaticDemo<br />

contains the static field x:<br />

public class StaticDemo<br />

{<br />

public static int x;<br />

}<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!