Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Techniques for aliasing in C#?

Tags:

c#

alias

Assume i want to create an alias of a type in C# using a hypothetical syntax:

 Currency = float;

Then i go away and create a few thousand files that use Currency type.

Then i realize that i prefer to use FCL types:

 Currency = System.Single;

Excellent, all code still works.

...months later...

Wait, i'm getting some strange rounding errors. Oh that's why, System.Single only has 7 digits of precision. Lets up that to 15 digits:

 Currency = System.Double;

...years later...

Ohhhh, floating point isn't exact; multiplying $0.0011/unit * 217,384 units exposes some limitations of using floating point. And accountants are sticklers against "accounting irregularities". No problem:

Currency = System.Decimal;

...years later...

International applications? Currency codes. Hmmmm. Thank you CodeProject:

 Currency = Money;

...later...

Ooo, patterns and practices. Let's obfuscate some of that code:

 Currency = ICurrency;

And during all this nonsense code didn't break.

i know C# doesn't support this level of encapsulation and resilency with the syntax i made up.

But can anyone suggest a syntax that can simulate what people have been trying to accomplish (including myself)?

like image 564
Ian Boyd Avatar asked Dec 15 '11 21:12

Ian Boyd


2 Answers

Create a class called Currency and implement (or delegate) the appropriate operators, then just change the class used to store the data internally when desired.

like image 138
Dylan Smith Avatar answered Oct 31 '22 06:10

Dylan Smith


You can use using like so: using Currency = System.Single;, but you must do it in every single file. But still easier to change, than searching for single in whole application.

like image 38
Krzysztof Avatar answered Oct 31 '22 06:10

Krzysztof