Dynamically declare method parameter type

I'm trying my best to describe this problem, but here it is:

Suppose now that I have a property type on one member of a class (instance):

Type t = propertyInfo.PropertyType; 

How to declare or set some variable to get the result of a method call later using the out keyword?

 t value; // Obviously doesn't compile, How do I declare this? // or this? //var value = default(t); // doesn't work someObject.GetData(out value); 

The premise here is that I don't have someObject, and I'm stuck with this method call signature.

+1
source share
2 answers

If there is, for example, a class:

 internal class Test { public void GetData(out int value) { value = 42; } } 

This method can be called using the Invoke () object, passing the [] object as arguments:

  var obj = new Test(); var type = obj.GetType(); var m = type.GetMethod("GetData"); var pars = new object[] { null }; m.Invoke(obj, pars); 
0
source

Maybe I donโ€™t understand something about the complexity of the problem, but if you have a compilation time instance of someObject , you can wrap this evil in the following way:

 class OutWrap<T,U> where T : U { private readonly SomeObject<T> obj; public OutWrap(SomeObject<T> obj) { this.obj = obj; } public T Value { get { T t; obj.GetData(out t); return t; } } } 

and use it:

 var evil = new SomeObject<int>(); // or however/whereever you get it from var wrap = new OutWrap<int, int>(evil); var output = wrap.Value; 
0
source

All Articles