tags:

views:

124

answers:

3

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;

    }

 }
+19  A: 

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

Jon Skeet
Beat me to it...deleted my post in shame yet again.
Justin Niessner
thanks, now I know what "where T : IBlah" means.
Blankman
+9  A: 

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);
  ...
}
JaredPar
Grrrreatt minds think alike :)
leppie
Ow. My head hurts. :)
John Kraft
so Func<T, int> takes T as a parameter and returns int? I thought Func<T, int> refers to both inputs to the getAge function.
Blankman
@Blankman, for Func, the last generic param is the type of the return type and all others are parameters. For Action, all generic params are for parameters.
JaredPar
Unless there is a very compelling reason to pass both the function and the object itself at the same time, I would recommend not doing it. Specifically, if you will only need that function in terms of the passed in object, you probably want to just curry the getAge function so your SomeMethod function is cleaner.
Albinofrenchy
+3  A: 

How about:

public class Blah
{
  public int SomeMethod(Func<int> get_age)
  {
    int blah = get_age();
    return blah;
  }
}
leppie
this is using a delegate?
Blankman
Yes, just a plain delegate.
leppie