Determine Type of Generic

L

Larry R

I am trying to determine the Type of the call to a Generic method:
public static void Main()
{
Check<string>();

}
public static void Check<T>()
{
Type n = T.GetType();
Console.WriteLine(n.Name );
}

Is there a way to do this?
 
A

Alberto Poblacion

Larry R said:
I am trying to determine the Type of the call to a Generic method:
public static void Main()
{
Check<string>();

}
public static void Check<T>()
{
Type n = T.GetType();
Console.WriteLine(n.Name );
}

Is there a way to do this?

Use typeof instead of GetType:

using System;

class Test
{
public static void Main()
{
Check<string>();
}
public static void Check<T>()
{
Type n = typeof(T);
Console.WriteLine(n.Name);
}
}
 
L

Larry R

Thanks Alberto! I was close on that!

So, what I was hoping to do is create a new type of that object and
use it
using System;
using System.Collections.Generic;

public class MyClass
{
public static void Main()
{
Check<MyItem>();
}
public static void Check<T>() where T:new()
{
Type n = typeof(T);
T obj = new n() ;
obj.Name="MyName";
Console.WriteLine(obj.Name);

}

}
class MyItem{
private string _name;
public string Name
{ get { return _name;}
set {_name = value; }
}
public MyItem(){ Console.WriteLine("Constr");}

}
 
A

Alberto Poblacion

Larry R said:
So, what I was hoping to do is create a new type of that object and
use it
[...]
Type n = typeof(T);
T obj = new n() ;

I don't understand why you are using a Type there. It's not that you
can't use Reflection on a Generic, it's just that I don't see the need. Why
don't you just use "new" on "T", since you already added the constraint
requiring a default constructor for T?

T obj = new T();
 
J

Jon Skeet [C# MVP]

Larry R said:
I am trying to determine the Type of the call to a Generic method:
public static void Main()
{
Check<string>();

}
public static void Check<T>()
{
Type n = T.GetType();
Console.WriteLine(n.Name );
}

Is there a way to do this?

Type t = typeof(T);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top