LB.
LB.

Reputation: 14112

Converting dynamic C# objects to array

Is there a way to convert a dynamic object to an array if it is either a single object of type Foo or Foo[] ?

For example,

if dynamic is Foo then convert to Foo[] with 1 object in array

if dynamic is an array Foo[] with n number of objects then convert to Foo[] with n number of objects in array.

Upvotes: 1

Views: 27401

Answers (3)

Jeff Mercado
Jeff Mercado

Reputation: 134811

By using a dynamic variable, the variable is dynamic, not the object the variable is referring to. That is, there is no static type checking when you want to access members of the object or want to convert it. You need some other magic to be able to do that.

You could wrap your Foo in a DynamicObject where you can specify how the conversion takes place.

public class DynamicWrapper<T> : DynamicObject
{
    public T Instance { get; private set; }
    public DynamicWrapper(T instance)
    {
        this.Instance = instance;
    }

    public override bool TryConvert(ConvertBinder binder, out object result)
    {
        if (binder.ReturnType == typeof(T))
        {
            result = Instance;
            return true;
        }
        if (binder.ReturnType == typeof(T[]) && binder.Explicit)
        {
            result = new[] { Instance };
            return true;
        }
        return base.TryConvert(binder, out result);
    }

    public override string ToString()
    {
        return Convert.ToString(Instance);
    }
}

Then you could do this:

dynamic dobj = new DynamicWrapper<Foo>(someFoo);
Foo foo1 = dobj;
Foo foo2 = (Foo)dobj;
Foo[] arr1 = (Foo[])dobj;
// someFoo == foo1 == foo2 == arr1[0]

dynamic darr = new DynamicWrapper<Foo[]>(arr1);
Foo[] arr2 = darr;
Foo[] arr3 = (Foo[])darr;
// arr1 == arr2 == arr3
// someFoo == arr2[0] == arr3[0]

Upvotes: 4

Amandalishus
Amandalishus

Reputation: 521

public Foo[] Create(dynamic fooOrFoos)
{
    return fooOrFoos.GetType().IsArray ? fooOrFoos as Foo[] : new Foo[] { fooOrFoos };
}

Perhaps I'm making this too easy... are you implying that you know nothing about what type the dynamic value might be?

Upvotes: 4

xanatos
xanatos

Reputation: 111830

I feel a little stupid... Is really this you want?

class Test
{
}

dynamic dyn = new Test();

Test[] tests = null;

if (dyn is Test)
{
    tests = new Test[] { (Test)dyn };
}
else if (dyn is Test[])
{
    tests = (Test[])dyn;
}

Upvotes: 9

Related Questions