Why does GetType on string property throw NullReferenceException?
When I call GetType on an int or DateTime property, I get the expected results, but on the 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 why? How is a string pointer different from an int-prop?
If the value is a property null
, you will get a NullReferenceException when trying to access object methods or properties, for example GetType()
. Primitive types such as int
and DateTime
are value types and therefore cannot contain a value null
, so GetType()
will not tolerate more than any of their other member functions.
Because the string is a reference type where the rest are not. DateTime and Int must have default values, they cannot be null.
What you need to understand is that the compiler creates a variable to store information. In C # 3.0, you don't need to explicitly declare it, but it still exists, so it creates a DateTime variable and an int variable and initializes them to their default values ββso as not to throw a compiler error. With a string, you don't have to do this (initialize the default) because it's a reference type.
To highlight what the other answers have pointed out, change int to int? and DateTime to DateTime? and try running the code again. Since these values ββcan now contain zeros, you will get the same exception.
The initial propString is null. We cannot execute null method. If you initialize propString: propString = "" then you can execute GetType () without exception
Code without exception:
private int PropInt { get; set; }
private DateTime PropDate { get; set; }
private string propString { get; set; }
propString = ""; // propString != null
WriteLine(PropInt.GetType().ToString()); // Result : System.Int32
WriteLine(PropDate.GetType().ToString()); // Result : System.DateTime
WriteLine(propString.GetType().ToString()); // Result : System.String