It doesn't compile because T could be anything, and not everything will have the myvar
field.
You could make myvar
a property on ITest
:
public ITest
{
string myvar{get;}
}
and implement it on the classes as a property:
public class MyClass1 : ITest
{
public string myvar{ get { return "hello 1"; } }
}
and then put a generic constraint on your method:
public void PrintGeneric<T>(T test) where T : ITest
{
Console.WriteLine("Generic : " + test.myvar);
}
but in that case to be honest you are better off just passing in an ITest:
public void PrintGeneric(ITest test)
{
Console.WriteLine("Generic : " + test.myvar);
}