views:

260

answers:

4

I am writing a financial application where the concept of 'Price' is used a lot. It's currently represented by the C# decimal type. I would like to make it more explicit and be able to change it to maybe double in the future, so I was thinking of creating a 'Price' struct that would basically act exactly the same as the decimal type (maybe add a bit of validation like must be greater than 0).

What do you think are the pros and cons of doing this?

+4  A: 

Structs should be used for small types that will (in my opinion) be immutable, i.e., value types. I am not sure what you mean by "used a lot", but if these structs will be passed around a lot in performance critical operations you will have to take into account the price of copying them versus the price of heap allocation. I doubt you will need to take that into account, but it is something to think about. I rarely find the need to use structs in my daily activities.

Also, as Jonathan points out, using the double type for money is a bad idea. The decimal type is much better suited to financial calculations.

Yet another aside; you will probably hear a lot of responses which talk about stack v heap allocation, so this article may interest you:

http://blogs.msdn.com/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx

Ed Swangren
Great article, a must read.
Michael Valenty
Thanks Michael, that's kind of you to say.
Eric Lippert
+4  A: 

Please don't use double for money. You'll have to remember to round it for display everywhere you use it at, and you have potential accuracy issues if you divide or multiply by large numbers. Decimal will give overflow errors, double will just lose accuracy. I'm not sure about you, but with money, I'd prefer an error and aborted operation to silently proceeding with a loss of accuracy.

If anything, based on projects I've been on, you may want to consider using a struct that has a decimal and some indication of what currency it is.

Jonathan
Thanks for the reminder. That is the reason I am using decimal right now. I am not planning to change it to double in the future, just be able to change it without having to refactor the entire application.
Hermann
A: 

Structs may not be so accessible from .NET languages other than C#. Rounding errors could be a problem too. Why not just create a Money class and store the value as a Decimal and the currency used.

BrianLy
Do you mean a class as opposed to a struct?
Hermann
I meant class. I've now updated my answer. Not sure why I got downvoted.
BrianLy
+1  A: 

There shouldn't be a reason to change the data type for a quantity like this; however, you may decide to add other information such as the currency or the number of decimal places to keep track of in calculations, so using a struct at this point will save you a LOT of time down the road.

Jon Seigel