Search code examples
c#propertiesinterfacegeneric-method

Generic method: Contraint with Interface, how to access properties


I want to access a property of a new created object within a generic method, which is constraint by an Interface:

public interface MyInterface
{
    int ID { get; set; }
    string Name { get; set; }
}

Since the Compiler knows that "T" is of the Type MyInterface it should be possible to access the properties of that inteface:

public T doSomething<T>(String value) where T : MyInterface, new()
{
    T entity =  new T();
    entity.Name = value;    
    return entity;
}

But it sais: T does not have a definition for 'Name'

If I can use an interface as a constraint here: Why isn't it possible to access its properties?


Solution

  • The code you posted is correct for itself. Maybe you have different versions of your interface (MyInterface in different namespaces)? Check the namespaces / fully qualified names of the interface types. Also the check the assembly versions, if declaring types in another assembly...