Click here to Skip to main content
11,642,216 members (60,225 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C#
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 21:23pm
Mehdi Gholam282.8K
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 at 20-Apr-12 3:34am
The type is only known at runtime, not compile time.
Reza Ahmadi at 20-Apr-12 3:37am
Then you need to use Reflection, or something like that.
Reza Ahmadi at 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
0 DamithSL 220
1 Sergey Alexandrovich Kryukov 154
2 Afzaal Ahmad Zeeshan 145
3 OriginalGriff 135
4 Mika Wendelius 80
0 Mika Wendelius 460
1 DamithSL 353
2 OriginalGriff 315
3 Sergey Alexandrovich Kryukov 179
4 Afzaal Ahmad Zeeshan 169

Advertise | Privacy | Mobile
Web04 | 2.8.150731.1 | Last Updated 20 Apr 2012
Copyright © CodeProject, 1999-2015
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