I am using a class as a wrapper to hold a group of several unsigned shorts that represent different options or characteristics. Each short is initialized to be a power of two so I can easily add or or them together.
public static class Options
{
public static readonly ushort OPTN0 = 1 << 0; // 0001
public static readonly ushort OPTN1 = 1 << 1; // 0010
public static readonly ushort OPTN2 = 1 << 2; // 0100
...
}
public static void main(string[] args)
{
funcThatUsesOptns(Option.OPTN0); // works fine
funcThatUsesOptns(Option.OPTN1 | Option.OPTN2); // fails because '|' returns int
funcThatUsesOptns((ushort)(Option.OPTN0 | Option.OPTN2)); // works fine
...
}
However, since "+" and "|" both return ints in this situation, I have to cast them every time I do. For example, both a and b are initialized as ints:
var a = Option.OPTN0 + Option.OPTN1;
var b = Option.OPTN0 | Option.OPTN1;
So I was wondering if operator overloading was possible for primitive types. If not, are there any better ways of achieving this? Of course it isn't going to kill me to just cast it every time, but I was hoping for a cleaner way.
Edit: I am actually using this to render a lot of simple geometric objects (cubes, pyramids,...). I would like to be able to quickly tell the renderer which faces to draw. If a face on one object is touching another or is facing away from the camera, I can set the corresponding bit to tell the renderer not to draw that face.
It seems like what you really want here are enum values based on ushort, like this:
[Flags]
public enum Options : ushort
{
OPTN0 = 1 << 0, // 0001
OPTN1 = 1 << 1, // 0010
OPTN2 = 1 << 2, // 0100
}
Then you can make use of the built-in |
operator for enums. You would, however, have to change the signature of your methods to access the Options
enum type instead of a ushort.
funcThatUsesOptns(Option.OPTN0 | Option.OPTN1);