I have an enumerated type that I would like to define the >
, <
, >=
, and <=
operators for. I know that these operators are implictly created on the basis of the enumerated type (as per the documentation) but I would like to explictly define these operators (for clarity, for control, to know how to do it, etc...)
I was hoping I could do something like:
public enum SizeType { Small = 0, Medium = 1, Large = 2, ExtraLarge = 3 } public SizeType operator >(SizeType x, SizeType y) { }
But this doesn't seem to work ("unexpected token") ... is this possible? It seems like it should be since there are implictly defined operators. Any suggestions?
All operators in C#.NET can be overloaded. We can use the new modifier to modify a nested type if the nested type is hiding another type. In case of operator overloading all parameters must be of the different type than the class or struct that declares the operator.
C does not support overloading of operators or functions. There's no way you can redefine < , <= , > , >= , == , or != to compare struct types directly.
No we cannot overload integer or float types because overloading means to change the working of existing operators or make them to work with objects int is single member not an object.
You can't do that. You can only provide overloaded operators for classes and structs you define -- and at least one of the parameters should be of type of the class or struct itself. That is, you can declare an overloaded addition operator that adds a MyClass
to MyEnum
but you can never do that with two MyEnum
values.
As other mentioned before, one cannot override operators on Enums, but you can do it on struct. See an example below. Let me know if it helped:
public struct SizeType { private int InternalValue { get; set; } public static readonly int Small = 0; public static readonly int Medium = 1; public static readonly int Large = 2; public static readonly int ExtraLarge = 3; public override bool Equals(object obj) { SizeType otherObj = (SizeType)obj; return otherObj.InternalValue.Equals(this.InternalValue); } public static bool operator >(SizeType left, SizeType right) { return (left.InternalValue > right.InternalValue); } public static bool operator <(SizeType left, SizeType right) { return (left.InternalValue < right.InternalValue); } public static implicit operator SizeType(int otherType) { return new SizeType { InternalValue = otherType }; } } public class test11 { void myTest() { SizeType smallSize = SizeType.Small; SizeType largeType = SizeType.Large; if (smallSize > largeType) { Console.WriteLine("small is greater than large"); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With