Why do I get the 'Operator '!=' can not be applied to operands of type Point and <null>' in this struct implementation

StackOverflow https://stackoverflow.com/questions/20702199

Question

I don't really know why I get this error while trying to validate the input value in the Property code here:

using ConsoleApplication4.Interfaces;

public struct Vector:IComparable
{
    private Point startingPoint;

    private Point endPoint;

    public Point StartingPoint  
    {
        get
        {
            return new Point(startingPoint);
        }
        set
        {
            if(value != null)
                this.startingPoint = value;
        }
    }

    public Point EndingPoint
    {
        get
        {
            return new Point(this.endPoint);
        }
        set
        {
            if(value != null)
                this.startingPoint = value;
        }
    }

The error that I get is on the lines where I have if(value!=null)

Was it helpful?

Solution

struct is a value type - it cannot be "null" like a class could be. You may use a Nullable<Point> (or Point?), however.

OTHER TIPS

Point is a struct and hence can't be null.

You can use Point? which is syntactic sugar for System.Nullable<Point>. Read more about nullable types at http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.120).aspx

If you want to compare to the default value of Point (which is not the same as null), then you can use the default keyword:

if(value != default(Point))

A struct is a value type, not a reference type. This implies, that it can never be null, especially, that its default value is not null.

Easy rule of thumb: If you need new(), it can be null. (This is a bit simplicistic, but devs knowing, when this might be wrong, most often don't need a rule of thumb)

I don't know what you are trying to achieve with your class, but it seems what you can simply write:

public struct Vector: IComparable
{
    public Point StartingPoint {get; set;}
    public Point EndPoint {get; set;}

    // implement IComparable
}

unless you intentionally want to create a copies of points (for whatever reason)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top