1

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?

Dave
  • 263
  • 3
  • 12
  • Do you have a `MyInterface` in another namespace? Have you done a clean and rebuild? – D Stanley Mar 26 '15 at 13:36
  • 1
    It works fine for me. I dont have any issue – Carbine Mar 26 '15 at 13:36
  • Is this really your _actual_ code? – ken2k Mar 26 '15 at 13:36
  • Yes it's another namespace but I integrated it by "using" statement. And no, this is not my actual code it's simplified. – Dave Mar 26 '15 at 13:43
  • mostly looks like namespace problem to me.Create a simple class and then try to implement your `MyInterface` in it. The complier will throw error if it is a namespace problem,let us know the error – Rohit Mar 26 '15 at 13:58

2 Answers2

1

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...

Udontknow
  • 1,472
  • 12
  • 32
1
    public class Foo2 : MyInterface
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

...

    var foo = doSomething<Foo2>("test");
    Console.WriteLine(foo.Name);

Seems to work as long as your code has the namespace of your interface and concrete class in a using clause. Also, as a matter of convention MyInterface should be IMyInterface.

BDH
  • 156
  • 8