Timothy Baldridge
Timothy Baldridge

Reputation: 10653

Get type of null array

I'm working on some serialization routines, and I need a way to get the type of an input array.

Let's say I have the following object:

class myclass {
    public int foo;
    public byte[] bar;
}

Now I can get the type of myclass.foo by using GetType(). And if I say that "myclass.bar = new byte[0]", I can infer that bar is an array of bytes by using GetElementType(), HasElementType, and IsArray.

However if I never set bar and just leave it as null, I can't find a way to get the type info off the object. If I do myclass.foo.GetType() all I get is a null value.

Is there anyway to infer the type of "bar" in this case?

Upvotes: 1

Views: 257

Answers (2)

dsolimano
dsolimano

Reputation: 8986

I think reflection should work -

typeof(myclass).GetField("bar").FieldType

Upvotes: 4

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421988

A nonexistent object doesn't have a type. It doesn't make sense to get the type of a null reference. What you are looking for is actually the type of the field. You can get that by reflecting over the type declaring the field (in this case, myclass).

Upvotes: 5

Related Questions