1

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?

o.k.w
  • 25,490
  • 6
  • 66
  • 63
Timothy Baldridge
  • 10,455
  • 1
  • 44
  • 80
  • Here's a related post on SO: http://stackoverflow.com/questions/1120839/net-c-reflection-list-the-fields-of-a-field-that-itself-has-fields – o.k.w Nov 19 '09 at 15:37

2 Answers2

5

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).

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
4

I think reflection should work -

typeof(myclass).GetField("bar").FieldType
dsolimano
  • 8,870
  • 3
  • 48
  • 63
  • 3
    I don't get a NullReferenceException with that code, nor should you (unless the field doesn't exist, in which case Type.GetField(string) will return null, but as long as your names are correct you shouldn't get a NullReferenceException). – jonp Nov 19 '09 at 15:28
  • dsolimano's method should work, MSDN's reference has something similar: http://msdn.microsoft.com/en-us/library/t0cs7xez.aspx – o.k.w Nov 19 '09 at 15:34