Blankman
Blankman

Reputation: 267320

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

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;

    }

 }

Upvotes: 5

Views: 193

Answers (3)

leppie
leppie

Reputation: 117350

How about:

public class Blah
{
  public int SomeMethod(Func<int> get_age)
  {
    int blah = get_age();
    return blah;
  }
}

Upvotes: 3

JaredPar
JaredPar

Reputation: 755537

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

Upvotes: 9

Jon Skeet
Jon Skeet

Reputation: 1503759

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

Upvotes: 19

Related Questions