tags:

views:

38

answers:

3

If I have a method signature like

public string myMethod<T>( ... )

How can I, inside the method, get the name of the type that was given as type argument? I'd like to do something similar to typeof(T).FullName, but that actually works...

+6  A: 

Your code should work. typeof(T).FullName is perfectly valid. This is a fully compiling, functioning program:

using System;

class Program 
{
    public static string MyMethod<T>()
    {
        return typeof(T).FullName;
    }
    static void Main(string[] args)
    {

        Console.WriteLine(MyMethod<int>());

        Console.ReadKey();
    }

}

Running the above prints (as expected):

System.Int32
Reed Copsey
Make sure to test it with MyMethod<int>>() and see what you get...you have to account for nullable types if you care for the underlying type in that scenario.
silverCORE
You mean "`<int?>`" If so, it works, but you get `System.Nullable<int>` (in full name syntax), which is what you'd expect...
Reed Copsey
Even though I already had the solution (although it didn't work for some reason...), I'll give you the rep points for writing the best answer by far =)
Tomas Lycken
@Tomas: Thanks ;) Sometimes it helps just knowing that it's NOT the problem...
Reed Copsey
A: 

Assuming you have some instance of a T available, it's no different than any other type.

var t = new T();

var name = t.GetType().FullName;
womp
You don't even need an instance of T.... typeof(T) works fine with no instance... Yours will give a different behavior if a subclass is passed into the method (as an argument)..
Reed Copsey
The problem with that code is that if T does not have a parameterless constructor then it will not work.
Nathan Taylor
@Nathan - it was just an example to show getting an instance of T. Presumably on a generic method he'll have some T type available. @Reed - you're correct of course, I assumed that was what he was after.
womp
A: 

typeof(T).Name and typeof(T).FullName are working for me...I get the type passed as argument.

silverCORE
ah. If the type you passed is Nullable, to get the underlying type you'd have to use something like typeof (T).GetGenericArguments()[0]
silverCORE
to check if the type if nullable, you'd use typeof(T).IsGenericType, and if it is, you'd use the following to get the Name or FUllName((Type)typeof(T).GetGenericArguments()[0]).Name
silverCORE