Sunday, February 13, 2011

Can C# generics have a specific base type?

Is it possible for a generic interface's type to be based on a specific parent class?

For example:

public interface IGenericFace<T : BaseClass>
{
}

Obviously the above code doesn't work but if it did, what I'm trying to tell the compiler is that T must be a sub-class of BaseClass. Can that be done, are there plans for it, etc.?

I think it would be useful in terms of a specific project, making sure a generic interface/class isn't used with unintended type(s) at compile time. Or also to sort of self-document: show what kind of type is intended.

  • public interface IGenericFace<T> where T : SomeBaseClass
    
    tvanfosson : You can find more info on how to constrain the type at http://msdn.microsoft.com/en-us/library/d5x73970(VS.80).aspx
    From Kyralessa
  • yes.

    public interface IGenericFace<T>
        where T : BaseClass
    {
    }
    
    Jason Bunting : this should be deleted, I don't see how it is adding anything - Kyralessa already answered this.
  • More info on Generic Interfaces: http://msdn.microsoft.com/en-us/library/kwtft8ak(VS.80).aspx

    From casademora
  • What your are referring to is called "Generic Constraints". There are numerous constraints that can be put on a generic type.

    Some baseic examples are as follows:

    • where T: struct - The type argument must be a value type. Any value type except Nullable -can be specified. See Using Nullable Types (C# Programming Guide) for more information.

    • where T : class - The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

    • where T : new() - The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

    • where T : <base class name> - The type argument must be or derive from the specified base class.

    • where T : <interface name> - The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

    • where T : U - The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.

    These can also be linked together like this:

    C#

    public class TestClass<T> Where T : MyBaseClass, INotifyPropertyChanged, new() { }
    public interface IGenericFace<T> where T : SomeBaseClass
    

    VB

    Public Class TestClass(Of T As {MyBaseClass, INotifyPropertyChanged, New})
    Public Interface IGenericInterface(Of T As SomeBaseClass)
    
    Jon Skeet : It would be worth changing the example - if you specify a base class name, that has to come before any interfaces. And you meant "new()" instead of "New()".
    Micah : Duly noted and changed.
    From Micah

0 comments:

Post a Comment