Is it possible to call a method on the type you pass into your generic method?
Something like:
public class Blah<T>
{
public int SomeMethod(T t)
{
int blah = t.Age;
return blah;
}
}
Is it possible to call a method on the type you pass into your generic method?
Something like:
public class Blah<T>
{
public int SomeMethod(T t)
{
int blah = t.Age;
return blah;
}
}
You can if there's some type to constrain T to:
public int SomeMethod(T t) where T : ISomeInterface
{
// ...
}
public interface ISomeInterface
{
int Age { get; }
}
The type could be a base class instead - but there has to be something to let the compiler know that there'll definitely be an Age
property.
(In C# 4 you could use dynamic typing, but I wouldn't do that unless it were a particularly "special" situation which actually justified it.)
Expanding on Jon's answer.
Yet another way is to take a functional approach to the problem
public int SomeMethod(T t, Func<T,int> getAge) {
int blah = getAge(t);
...
}