Joan Venge
Joan Venge

Reputation: 330852

Nullable value types

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?

Upvotes: 0

Views: 557

Answers (5)

Yuriy
Yuriy

Reputation:

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

Upvotes: 1

Svish
Svish

Reputation: 157971

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.

Upvotes: 1

BFree
BFree

Reputation: 103742

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.

Upvotes: 3

bdukes
bdukes

Reputation: 155895

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.

Upvotes: 2

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421968

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.

Upvotes: 10

Related Questions