Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a GetType on a string-property result in a NullReferenceException?

When I call a GetType on a int- or a DateTime-property, I get the expected results, but on a string-property, I get a NullReferenceException (?) :

private int      PropInt    { get; set; }
private DateTime PropDate   { get; set; }
private string   propString { get; set; }

WriteLine(PropInt.GetType().ToString());    // Result : System.Int32
WriteLine(PropDate.GetType().ToString());   // Result : System.DateTime
WriteLine(propString.GetType().ToString()); // Result : NullReferenceException (?!)

Can someone explain how come ? In what way differs a string-prop from a int-prop ?


1 Answers

If the property's value is null, then you'll get a NullReferenceException when trying to access object methods or properties, like GetType(). Primitive types like int and DateTime are value types, and as such cannot hold a null value, which is why GetType() won't fail any more than any of their other member functions.

like image 105
Adam Robinson Avatar answered Jun 23 '26 16:06

Adam Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!