Operator '==' cannot be applied to operands of type 'Type?' and 'Type?'

9k views Asked by At

I have a class like this:

public class Article {

private Category? category;
private string content;

public Article(Category? category,string content){
      Contract.Ensures(this.category == category); // error

   }
}

but on Ensure method this error occurs:

Operator '==' cannot be applied to operands of type 'Category?' and 'Category?'

How can I avoid that?

3

There are 3 answers

0
Servy On BEST ANSWER

You'll need to overload the == operator for that type if you expect to be able to use it to compare two instances (whether nullable or not) of that type.

5
overflowed On

Use this:

this.category.Equals(category)
1
ymz On

first please implement Equals inside Category class

public struct Category // turned out that Category is a struct
{
    public int Field {get; set; } // for demo purpose only

    public override bool Equals(Object that) 
    {
         if (that == null)
         {
             return false;
         }
         else
         {
             if (that is Category)
             {
                 // select the fields you want to compare between the 2 objects

                 return this.Field == (that as Category).Field;
             }

             return false;
         }
    }
}

then in your code you can use equals method

Contract.Ensures(this.category.Equals(category))