Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call a method on the type you pass into your generic method?

Tags:

c#

generics

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;

    }

 }
like image 756
Blankman Avatar asked Jul 08 '09 13:07

Blankman


People also ask

Can a non generic class have a generic method?

Yes, you can define a generic method in a non-generic class in Java.

Can methods be generic?

Just like type declarations, method declarations can be generic—that is, parameterized by one or more type parameters.

Which of the following reference types Cannot be generic?

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 .


2 Answers

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

like image 194
Jon Skeet Avatar answered Nov 15 '22 07:11

Jon Skeet


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);
  ...
}
like image 41
JaredPar Avatar answered Nov 15 '22 08:11

JaredPar