I have a bunch of code that has lots integers with different meanings (I’d rather a general solution but for a specific example: day-of-the-month vs. month-of-the-year vs. year etc.). I want to be able to overload a class constructor based on these meanings.
For example
int a; // takes role A int b; // takes role B var A = new Foo(a); // should call one constructor var B = new Foo(b); // should call another constructor
Now clearly that won’t work but if I could define a type (not just an alias) that is an int in all but name like this:
typedef int TypeA; // stealing the C syntax typedef int TypeB;
I could do the overloading I need and let the type system keep track of what things are what. In particular this would allow me to be sure that values are not mixed up, for example a value returned from a function as a year is not used as a day-of-the-month.
Is there any way short of class or struct wrappers to do this in c#?
It would be nice if the solution would also work for floats and doubles.
There is no direct typedef equivalent, but you can do the following:
However, this just aliases the type rather than creating a new strong type. Therefore, the compiler will still treat them as an
intwhen resolving method calls.A better solution might be to create simple wrapper classes that wraps
intand provides implicit casting, such as:However, in most situations, an
enumwould be more appropriate.