Click here to Skip to main content
Rate this: bad
good
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
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 19-Apr-12 21:23pm
Mehdi Gholam236.3K
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi,
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;
method<int32>(iObj);
 
or
 
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
  Permalink  
v2
Comments
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.
 
Cheers
Rate this: bad
good
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);
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 318
1 Sergey Alexandrovich Kryukov 286
2 RyanDev 75
3 PhilLenoir 60
4 nv3 60
0 Sergey Alexandrovich Kryukov 6,691
1 OriginalGriff 6,119
2 CPallini 2,473
3 Richard MacCutchan 1,697
4 Abhinav S 1,560


Advertise | Privacy | Mobile
Web01 | 2.8.140821.2 | Last Updated 20 Apr 2012
Copyright © CodeProject, 1999-2014
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