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;
}
}
Yes, you can define a generic method in a non-generic class in Java.
Just like type declarations, method declarations can be generic—that is, parameterized by one or more type parameters.
Almost all reference types can be generic. This includes classes, interfaces, nested (static) classes, nested interfaces, inner (non-static) classes, and local classes. The following types cannot be generic: Anonymous inner classes .
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);
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With