user1146081
user1146081

Reputation: 195

C#: How to access array methods from parent object?

My ctor return an object which is multidimentional array. Depends on constructor argument, the object returned by ctor can be different rank array, but always int.

object arr = new int[2,2,2];

or

object arr = new int[2,2,2,2,2];

or

object arr = new int[0,0];

Having arr object constructed, and knowing what it is (GetType()), I'd like to access array methods like Rank, GetLength, GetValue etc. How I can access child specific methods from the object level? For now I have only four methods for arr object accessible: Equals, GetHashCode, GetType, and ToString

Upvotes: 0

Views: 163

Answers (3)

cnom
cnom

Reputation: 3241

You have to cast it back to an Array object and then these methods will be available!

Upvotes: 0

Paolo Tedesco
Paolo Tedesco

Reputation: 57222

You could just declare your variable as Array:

Array arr = new int[2,2,2,2,2];
int rank = arr.Rank;

Or cast to Array:

object arr = new int[2,2,2,2,2];
Array array = (Array)arr;

Upvotes: 1

blas3nik
blas3nik

Reputation: 1381

Cast the object into an array, like this:

((int[])arr).Rank
((int[])arr).GetLength()

or

(arr as int[]).Rank

Upvotes: 1

Related Questions