Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics where T is class implementing interface

Tags:

I have a interface:

interface IProfile { ... }

...and a class:

[Serializable]
class Profile : IProfile 
{ 
  private Profile()
  { ... } //private to ensure only xmlserializer creates instances
}

...and a manager with method:

class ProfileManager
{
  public T Load<T>(string profileName) where T : class, IProfile
  {
    using(var stream = new .......)
    {
      var ser = new XmlSerializer(typeof(T));
      return (T)ser.Deserialize(stream);
    }
  }
}

I expect the method to be used like this:

var profile = myManager.Load<Profile>("TestProfile"); // class implementing IProfile as T

...and throw compile time error on this:

var profile = myManager.Load<IProfile>("TestProfile"); // NO! IProfile interface entered!

However everything compiles, and only runtime errors is thrown by the XmlSerializer.

I thought the where T : class would ensure only class types where accepted?

Is it possible to make the compiler throw error if IProfile (or other interfaces inheriting from IProfile) is entered, and only types classes implementing IProfile are accepted?

like image 896
Anders Avatar asked Mar 07 '14 10:03

Anders


People also ask

Can a generic class implement an interface?

Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.

What is a generic interface?

A generic interface is primarily a normal interface like any other. It can be used to declare a variable but assigned the appropriate class. It can be returned from a method. It can be passed as argument. You pass a generic interface primarily the same way you would an interface.

Can a generic class extend an interface?

Java Generic Classes and SubtypingWe can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.


1 Answers

According to MSDN class means that T must be a reference type; this applies also to any class, interface, delegate, or array type.

One work around would be to require that T implements the parameter less constructor so:

where T : class, IProfile, new()
like image 96
Bob Vale Avatar answered Nov 09 '22 06:11

Bob Vale