Array element type

J

jtougas

What is the way to the type of an array's elements?

Array a = new long[] { 1, 2, 3 };
Type t = a.GetType();
Console.WriteLine( t.FullName );

This will write "System.Int64[]", but is not what I'm looking for.
Rather I want the type of the array's elements, so "System.Int64". I
seem to remember something along the lines of "a.GetElementType()" but
I can 't find anyting of the sort anymore.

Cheers
 
J

Jon Skeet [C# MVP]

What is the way to the type of an array's elements?
Type.GetElementType()

Array a = new long[] { 1, 2, 3 };
Type t = a.GetType();
Console.WriteLine( t.FullName );

This will write "System.Int64[]", but is not what I'm looking for.
Rather I want the type of the array's elements, so "System.Int64". I
seem to remember something along the lines of "a.GetElementType()" but
I can 't find anyting of the sort anymore.

Right method, wrong type :)
 
J

jtougas

Nevermind, found it...

Array a = new long[] { 1, 2, 3 };
Type t = a.GetType().GetElementType();
Console.WriteLine( t.FullName );
 
S

Stoitcho Goutsev \(100\)

Hi,

What about

Type t = a[0].GetType();

The method I believe you said you forgot I guess is

Type t = a.GetType().GetElementType();

GetElementType is method of the Type class not the Array class.
 
J

Jon Skeet [C# MVP]

Stoitcho Goutsev (100) said:
What about

Type t = a[0].GetType();

There are three problems with that:

1) The array might be empty
2) For reference types, the first element might be null
3) For reference types, the type of the actual object referred to could
be derived from the type of the array element (eg object[] with the
first element being a string)
The method I believe you said you forgot I guess is

Type t = a.GetType().GetElementType();

GetElementType is method of the Type class not the Array class.

Yup.
 
S

Stoitcho Goutsev \(100\)

What about
Type t = a[0].GetType();

There are three problems with that:

1) The array might be empty
2) For reference types, the first element might be null
3) For reference types, the type of the actual object referred to could
be derived from the type of the array element (eg object[] with the
first element being a string)

Yes, I know that. I was refering to the concrete example. That was most like
a joke :) This was the reason I gave the real solution too.
Thanks for the clarification.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top