Click here to Skip to main content
15,938,218 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Say I have a method with generic parameters, how do I enter:
doSomething<foo.GetType()>();


Why doesn't this work and how can I make this work?
Posted
Comments
Kornfeld Eliyahu Peter 19-Jan-14 4:41am    
I think you can't do this in a simple way like in your example.
You may need a lot of reflection...
Read here http://msdn.microsoft.com/en-us/library/4xxf1410(v=vs.110).aspx

As I know, foo.GetType() is invoked at runtime, so you should try by using typeof(foo) that is managed at compile time.
 
Share this answer
 
Why? Simple: because you have no parameters, the decision as to what type to call your method with is decided at compile time - the type cannot be inferred from the usage. Which mean you have to provide a constant type specifier, rather than a method call.

Instead, try this:
C#
private void DoSomething<T>()
    {
    Console.WriteLine("DoSomething:" + typeof(T));
    }
private void DoSomething<T>(T x)
    {
    Console.WriteLine("DoSomething:" + x.GetType());
    }
Then you can call it:
C#
DoSomething<int>();
DoSomething<float>();
double d = 12.34;
DoSomething(d);
And get what you want:
DoSomething:System.Int32
DoSomething:System.Single
DoSomething:System.Double
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900