Tutorial :Nullable value types



Question:

If a value type is declared nullable, how should I take precautions for this? I.e. if in the constructor I have:

public Point3 ( Point3 source )  {      this.X = source.X;      this.Y = source.Y;      this.Z = source.Z;  }  

would it fail, if source was null?


Solution:1

I don't see the possibility of Point3 being null if it's a value type. Don't you miss a question mark? And if you really mean Point3?, then you should access it like:

public Point3 ( Point3? source )  {      this.X = source.Value.X;      this.Y = source.Value.Y;      this.Z = source.Value.Z;  }  

and in this case, the Value property will throw an exception if it's null.


Solution:2

The caller of this method will not be able to pass in a nullable point, since the method takes a regular point, not a Nullable one. Therefore, you don't need to worry about Point being null in your constructor code.


Solution:3

Yes, that would fail if source was null.

You'll have to decide what the correct behavior should be if source is null. You might just throw an exception.

public Point3 ( Point3? source )  {      if (source == null)       {          throw new ArgumentNullException("source");      }        this.X = source.Value.X;      this.Y = source.Value.Y;      this.Z = source.Value.Z;  }  

Or, if you don't want to accept null values for source, just keep the method as you have it in your example. That method doesn't accept a Nullable<Point3>, so you don't have to worry about it being null in that case.


Solution:4

If source was a Point3? it wouldn't be a Point3. So as far as I know, it would fail compile time. To send in a Point3? you would have to use .Value, which would throw an exception I believe if it was null.


Solution:5

    public Point3(Point3? source) {          this.X = source.GetValueOrDefault().X;           this.Y = source.GetValueOrDefault().Y;          this.Z = source.GetValueOrDefault().Z;       }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »