Override objects return value
c#
Solution
May be operator is the case?
public class SomeClass {
...
public static int operator -(SomeClass left, int right) {
if (Object.ReferenceEquals(null, left))
throw new ArgumentNullException("left");
return left.getCurrentValue() - right;
}
}
...
SomeClass someClassInstance = new SomeClass(...);
int result = someClassInstance - 5;
Another possibility (based on implicit operator) is to convert SomeClass implicitly to `int` whenever required:
public class SomeClass {
...
// Whenever int is requiered, but SomeClass exists make a conversion
public static implicit operator int(SomeClass value) {
if (Object.ReferenceEquals(null, value))
throw new ArgumentNullException("value");
return value.getCurrentValue();
}
}
...
SomeClass someClassInstance = new SomeClass(...);
int result = someClassInstance - 5;
Problem
I'm trying to compare an object with an int value such as ``` if (myObject - 5 == 0) doSomething(); ``` my class could look something like this: (most setters/getters removed, so don't mind that all variables are private) ``` public class SomeClass { public string name; private int minValue; private int maxValue; private int currValue; public int getCurrentValue() { return currValue; } } ``` What I'm trying to achieve is something like this: ``` someClassInstance - 5; ``` to be equal ``` someClassInstance.getCurrentValue() - 5; ``` Can I make an override for the object to act as an int (it's own variable) opposed to just being an object?