is there any way to do this on a class and still retain the capability to detect whether a variable of the Type is null ? I can do this for structs, (cause struct can't really be null, with a struct, instead of comparing x with null, you use a separate method caleld IsNull or HasValue... but you can't use that technique with a class cause when the class variable is null, of course, you can't call such an instance method on it !
public class myClass: IEquatable<myClass> { public int IntValue { get; set; } public static bool operator ==(myClass cA, myClass cB) { return cA is myClass && cB is myClass && cB.Equals(cA); } public static bool operator !=(myClass cA, myClass cB) { return !(cA == cB); } public override bool Equals(object o) { return o is myClass && this == (myClass)o; } public override bool Equals(myClass o) { return IntValue == o.IntValue; } } but when I go:
myClass x; if (x != null) // this returns false when it should be true { //code to execute with x here } For what it's worth, the only reason I want this to be a class is because it participates in a simple inheritance relationship. This is an immutable class, and in effect what I am trying to do here is code it so it can behave like an immutable and nullable class, exactly like an immutable, nullable struct behaves (such as Nullable<int> or Nullable<float> etc.
isoperator calls inpublic static bool operator ==(myClass cA, myClass cB) { return cA is myClass && cB is myClass && cB.Equals(cA); }are not needed.