I was reading a Business Primitives by CodeBetter.com and was toying around with the idea.
Taking his example of Money, how would one implement this in a way that it can be used similarily as regular value types?
What I mean by that is do this:
Money myMoney = 100.00m;
Instead of:
Money myMoney = new Money(100.00m);
I understand how to override all the operators to allow for functionality doing math etc, but I don’t know what needs to be overriden to allow what I’m trying to do.
The idea of this is to minimize code changes required when implementing the new type, and to keep the same idea that it is a primitive type, just with a different value type name and business logic functionality.
Ideally I would have inherited Integer/Float/Decimal or whatever required, and override as needed, however obviously that is not available to structures.
You could provide an implicit cast operator from
decimaltoMoneylike so:Usage:
Now, what is happening here is not that we are overloading the assignment operator; that is not possible in C#. Instead, what we are doing is providing an operator that can implicitly cast a
decimaltoMoneywhen necessary. Here we are trying to assign the decimal literal100mto an instance of typeMoney. Then, behind the scenes, the compiler will invoke the implicit cast operator that we defined and use that to assign the result of the cast to the instancemoneyofMoney. If you want to understand the mechanisms of this, read §7.16.1 and §6.1 of the C# 3.0 specification.Please note that types that model money should be
decimalunder-the-hood as I have shown above.