Search code examples
javac#arraylistxamarincode-translation

need help translating a code snippet from java to C# equivalent


Here's the code snippet I'd like to translate from Java to C#. I'm not sure what's causing the error but I've never used ArrayLists and vectors before. Thanks in advance!!

//Java class definitions, constructors, fields, methods etc here. 
//sphbasis is a Vector object.

    public SphericalHarmonicDecomposition[] getSphericalHarmonicBasis() {
    return (SphericalHarmonicDecomposition[])(sphbasislist.toArray(
    new SphericalHarmonicDecomposition[sphbasislist.size()]));
}

I've tried doing the following in C#:

//C# class definitions, constructors, fields, methods etc here. 
//sphbasis is a ArrayList object.

    public SphericalHarmonicDecomposition[] getSphericalHarmonicBasis() {
    return (SphericalHarmonicDecomposition[])(sphbasislist.ToArray(
    new SphericalHarmonicDecomposition[sphbasislist.Count]));
    }

I get the following errors. I'm using Mono and Xamarin studio on a mac.

Error CS1502: The best overloaded method match for 
`System.Collections.ArrayList.ToArray(System.Type)' 
has some invalid arguments (CS1502) (projectx)

and

Error CS1503: Argument `#1' cannot convert    
`matdcal.engine.model.SphericalHarmonicDecomposition[]' expression 
to type `System.Type' (CS1503) (projectx)

Solution

  • Please try the following. In Java you need to pass an array to the toArray method, but that's not correct in C# (.NET).

    //C# class definitions, constructors, fields, methods etc here. 
    //sphbasis is a ArrayList object.
    
        public SphericalHarmonicDecomposition[] getSphericalHarmonicBasis() {
        return (SphericalHarmonicDecomposition[])(sphbasislist.ToArray());
        }
    

    References

    Java ArrayList.toArray

    C# List.ToArray