Thursday, February 02, 2006

A good way to create a custom Value-Type object in C#?

Have you ever written code like this?

State state = new State("AZ");
Money money = new Money(299.95);
 
State state = State.Parse("AZ");
Money money = Money.Parse(299.95);

How many domain-specific Value Type classes (you care about equality but not identities) have you been creating every project? The question of should I use the "new" keyword or a static .Parse() method to create them is always a coding consistency problem.

What if I tell you that you can do this in C#:

State state = "AZ";
Money money = 299.95;

Simple and clean. Here's how:

public class State
{
    private readonly string _state;
 
    private State(string state)
    {
        _state = state;
    }
 
    public static implicit operator State(string state)
    {
        return new State(state);
    }
}