2

I got error which is object must implement IConvertible when converting array to b[] class. The code as follows:

public void Main()
{
    ArrayList myList = new ArrayList(); 
    a a1 = new a();
    b ba = new b();
    ba.b1 = 1;
    ba.b2 = 2;
    myList.Add(ba);
    a1.Bclass = ConvertType(myList.ToArray(), GetArrayType(Type.GetType("b")));
}

private Type GetArrayType(Type elementType)
{
    return elementType.MakeArrayType();
}

public static dynamic ConvertType(dynamic source, Type dest)
{
    return System.Convert.ChangeType(source, dest);
}

I would like to do this instead of direct casting since I wanted to do it dynamically. The example classes are as follows:

public class a
{
    private b[] bclass;
    public b[] Bclass
    {
        get;
        set;
    }
}

public class b
{
    public int b1
    {
        get;
        set;
    }

    public int b2
    {
        get;
        set;
    }
}
user3120873
  • 31
  • 1
  • 1
  • 5
  • 1
    In the duplicate note, that your type has to implement `IConvertible`, which your types don´t seem to. – MakePeaceGreatAgain Jan 25 '18 at 08:10
  • @HimBromBeere the problem is not the IConvertible. The problem lies in the fact that the code tries to 'convert' (not cast) an object into the type he wants. Basically, to solve use the arraylist.ToArray(typeof(B)) instead and it should work fine. – RMH Jan 25 '18 at 08:13
  • @RMH if I use myList.ToArray(typeof(b)) I need to add (b[]) myList.ToArray(typeof(b)) and it works. But I want it when **b[]** is only known at run-time. – user3120873 Jan 25 '18 at 08:21
  • @user3120873 How do you mean 'only known at run-time'? Does the type not yet exist and do you create it dynamically? – RMH Jan 25 '18 at 08:28
  • @RMH My apologies, I mean I wanted to create it dynamically. In way that I want to convert it dynamically instead of using this (b[]) myList.ToArray(typeof(b)) . – user3120873 Jan 25 '18 at 09:16

0 Answers0