retrieving the type of a generic Type argument

Hello,

I have a question considering generics.If we take the next code snippet:

public abstract class TypedResourceRetriever<T>{

public Type ResourceType{
get {
return T;
}
}
}

This code does not work. I wonder why microsoft did not make this work.
It would be really handy for me to have this feature in the C# language.

I solved the problem with the code below:

public abstract class TypedResourceRetriever<T>{

public Type ResourceType{
get {
Type t = this.GetType();
while (! t.Name.StartsWith("TypedResourceRetriever")){
t = t.BaseType;
}
return t.GetGenericArguments()[0];
}
}
}

Obviously this is not the way to do it.
(if someone overrides this class using a classname which starts with TypedResourceRetriever
we definitly have trouble)

So my question is wether anyone knows a better way to solve this problem.

Kind regards,

herman lindner



Answer this question

retrieving the type of a generic Type argument

  • csann

    (Don't you just love delays in seeing answers )

    Jon



  • hela

    Just change the return statement to

    return typeof(T);

    Jon



  • ctssoms

    herm wrote:

    public abstract class TypedResourceRetriever<T>{

    public Type ResourceType{
    get {
    return T;
    }
    }
    }

    I think you want to change "return T" to "return typeof(T)". Is that what you're after


  • TheMaj0r

    Hee Guys,

    thanx for the help this was indeed what i was looking for.


  • John12312

    public abstract class TypedResourceRetriever<T>{

    public Type ResourceType{
    get {
    return typeof(T);
    }
    }
    }


  • retrieving the type of a generic Type argument