Click here to Skip to main content
15,880,405 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Say we have :
C#
public void method<T>(T obj)
{
   // some stuff done on the obj
}

And we have deserialized an object and we need to pass
C#
object obj = CreateObject(bytearray); // serialized byte[] of object
method(obj);

Now the problem is that method needs to know the object type for it to work (internal generics) but we are passing an object, so it will fail. However the CreateObject method can determine the type and it recreates the original without problem.

The question is : how can we somehow give the type information to method so it doesn't break at runtime?
Posted

Hi,
I presume you want to pass the type using the Generics syntax. If so, you can pass it using something like this:

C#
Int32 iObj=0;
method<int32>(iObj);


or

C#
Stack sObj = new Stack();
method<stack>(sObj);


I'm not sure if your point is another mean of sending type to the 'method' method?

Cheers
 
Share this answer
 
v2
Comments
Mehdi Gholam 20-Apr-12 3:34am    
The type is only known at runtime, not compile time.
Reza Ahmadi 20-Apr-12 3:37am    
Then you need to use Reflection, or something like that.
Reza Ahmadi 20-Apr-12 3:42am    
Another way might be using interface for a wide range of types in order to make them usable in your method. I think I got your point but it does not seem to be possible in C# compiler.

Cheers
Found the solution as :
C#
object obj = CreateObject(bytearray);

var mi = this.GetType().GetMethod("method", BindingFlags.Instance | BindingFlags.NonPublic);
var m = mi.MakeGenericMethod(new Type[] { obj.GetType() });
m.Invoke(this, new object[] { obj }); // instead of method(obj);
 
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