Click here to Skip to main content
13,287,315 members (51,351 online)
Rate this:
Please Sign up or sign in to vote.
See more:
Say we have :
public void method<T>(T obj)
   // some stuff done on the obj

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

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 19-Apr-12 22:23pm
Mehdi Gholam348.6K
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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

Int32 iObj=0;


Stack sObj = new Stack();

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

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.

Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Found the solution as :
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);

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.171207.1 | Last Updated 20 Apr 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100