TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Generics: Base Class Constraint

How cool is this?! OK, maybe I get a little overexcited about new features and specifically new features that work with intellisense. In .NET v2.0, if I create a generic class with a base type constraint, any instance of the generic type parameter allows me to see use the base class's (that is defined as the constraint) properties and methods The base class constraint means that the type argument must be or derive from the specified base class. So, if I create a Shape class that has a Draw method, I can call t.Draw() in my generic class...

abstract class Shape {

    abstract void Draw();

}

 

 

class Circle : Shape {

    private override void Draw() {

        throw new NotImplementedException();

    }

}

 

class SomeGenericClass<T> where T : Shape {

    T t = null;

 

    public void SomeMethod() {

        //Can call draw on t due to the constraint

        t.Draw();

    }

}


Digg!

posted on Tuesday, January 18, 2005 12:24 PM

Feedback

# re: Generics: Base Class Constraint 1/21/2005 7:21 AM Scott Allen

That is cool...