1

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.

1
  • Just to understand, if the object is a Foo[] array then just keep it that way? Commented Oct 20, 2011 at 19:27

3 Answers 3

9

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;
}
Sign up to request clarification or add additional context in comments.

Comments

4
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?

Comments

4

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]

2 Comments

+1 but I have to ask why you are saveing MyType and MyTypeArray when you have T (and for the array you have T[])
Scratch that, what am I thinking? Of course! typeof(T[]). For a while there, I thought I couldn't do that. Thanks for pointing that out. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.