简体   繁体   中英

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 ?

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.

Because string is a reference type where the others are not. The DateTime and the Int have to have values by default, they can't be null.

What you have to understand is the the compiler is creating a variable for you to store the information. In C# 3.0 you don't have to explicitly declare it, but it is still there, so it's creating a DateTime variable and an int variable and initializing them to their default values so not to cause a compiler error. With a string, it doesn't need to do this (initialize a default value), because it's a reference type.

To emphasize what the other answers have indicated, change int to int? and DateTime to DateTime? and try running the code again. Since those values can now hold nulls, you will get the same exception.

Initial value of propString is null. We cann't execute method of null. If you initialaze 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM