Pretzel
Pretzel

Reputation: 8301

Auto-properties: Checking/validating during the "set"

I think we can all agree that Automatic Properties in C# 3.0 are great. Something like this:

private string name;
public string Name
{
    get { return name; }
    set { name = value; }
}

Gets reduced to this:

public string Name { get; set; }

Lovely!

But what am I supposed to do if I want to, say, convert the Name string using the ToUpperInvariant() method while "setting". Do I need to revert back to the old C# 2.0 style of creating properties?

    private string name;
    public string Name
    {
        get { return name; }
        set { name = value.ToUpperInvariant(); }
    }

Or is there a more elegant way of accomplishing this?

Upvotes: 3

Views: 1200

Answers (1)

tanascius
tanascius

Reputation: 53944

Yes, you have to convert it back. An autoproperty can't do this kind of checks.

Upvotes: 5

Related Questions