Click here to Skip to main content
Sign Up to vote bad
good
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:23


2 solutions

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  
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  
Comments
Mehdi Gholam - 20 Apr '12 - 3:34
The type is only known at runtime, not compile time.
Reza Ahmadi - 20 Apr '12 - 3:37
Then you need to use Reflection, or something like that.
Reza Ahmadi - 20 Apr '12 - 3:42
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

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Mohammed Hameed 268
1 Sergey Alexandrovich Kryukov 238
2 OriginalGriff 236
3 Mayur_Panchal 153
4 Dave Kreskowiak 125
0 Sergey Alexandrovich Kryukov 8,171
1 OriginalGriff 6,236
2 CPallini 3,482
3 Rohan Leuva 2,703
4 Maciej Los 2,234


Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 20 Apr 2012
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid