1

I am struggling to describe this problem I have, but here it is:

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

 Type t = propertyInfo.PropertyType;

How do I declare or setup some variable, in order to receive a method call result 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 own someObject and I am stuck with this method call signature.

alpinescrambler
  • 1,934
  • 16
  • 26
  • 1
    your best bet is to use value as 'object' type. – ANewGuyInTown Oct 26 '15 at 05:20
  • unfortunately the GetData method doesn't have that signature – alpinescrambler Oct 26 '15 at 05:23
  • 1
    [This SO](http://stackoverflow.com/questions/3652503/how-to-pass-transfer-out-parameter-as-reflection-visual-studio-extensibility) should help you. – Siva Gopal Oct 26 '15 at 05:39
  • Try to use `Activator.CreateInstance(t)`. Or you can call `t.GetConstuctors(...)[index].Invoke()`. – qxg Oct 26 '15 at 06:16
  • It's very hard to understand the problem here - what *do* you know about `GetData`? What is the type of `someObject`? – Jon Skeet Oct 26 '15 at 15:15
  • someObject is a utility class, which I don't have control, and has multiple GetData(out value) method signatures. I need to match the signature call, given the type "t" information that I have in the example. – alpinescrambler Oct 27 '15 at 16:26

2 Answers2

0

If there is for example a class:

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

The method can be called with Invoke() passing 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);
Martin Staufcik
  • 8,295
  • 4
  • 44
  • 63
0

I may be misunderstanding something about the complexity of the problem here, but, if you have a compile time instance of someObject, you can wrap the evil up like this:

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;
jdphenix
  • 15,022
  • 3
  • 41
  • 74