Casting Question

I have an ArrayList in which each element contains an Integer. I'd like to convert this to a Decimal Array.

So I tried making the conversion like this:

(decimal[]) MyIntegerArrayList.ToArray(typeof(decimal))

but it fails.


Is there a simple way to make this conversion

Robert


Answer this question

Casting Question

  • pexxx

    Gentlemen,

    Your "ConvertAll" suggestion must require VS2005. I'm only using VS2003. So I guess I'm going to have to write my own conversion method and convert each element, one by one.

    Oh well, at least I know that I wasn't "missing" something very simple.

    Thank you for responding,

    Robert


  • Priya Shekhar

    From your ArrayList, you can easily create a int[] with the method you already used. Then, to convert the int[] to decimal[] you can use Array.ConvertAll<>.

    Using Array.ConvertAll<> usually means that you must provide a method to convert each element of the array from one type to another, but for simple types you can usually resort to the Convert class.

    In your case, it all boils down to:

    decimal [] myDecimalArray = Array.ConvertAll<int, decimal> ((int []) MyIntegerArrayList.ToArray (typeof (int)), Convert.ToDecimal);

    HTH
    --mc


  • gokhanmutlu

    Hi

    I think that this is a simple way:

    Conversion:

    Decimal[] DecimalArray = Array.ConvertAll(IntegerArray, new Converter<Int32, Decimal>(MyConversionMethod));

    and MyConversionMethod :


    private Decimal MyConversionMethod(Int32 i)
    {
    return Convert.ToDecimal(i);
    }

    Yours

    Markku


  • Casting Question