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?

+2


source to share


4 answers


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.



+8


source


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.

+2


source


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.

+2


source


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

      

+1


source







All Articles