3

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?

Pretzel
  • 8,141
  • 16
  • 59
  • 84
  • 1
    I am afraid you are stuck with the C# 2.0 way. – ChaosPandion Jul 20 '10 at 14:52
  • 1
    I would argue that mutating the value such that an external caller will not get the same value out that was set is a "side-effect" and not desirable (ie: string s = "blah"; foo.Name = s; (foo.Name==s) is sometimes false which is unexpected to a consumer of your class) You should probably leave it as an auto-property and perform ToUpperInvariant(); internally when you need to use it, or provide a private-only property with only a getter that performs the ToUpperInvariant(). – David Jul 20 '10 at 14:56
  • @David: The same thought had crossed my mind. I'm still undecided as to which way I want it to operate. In the specific case that I'm working on right now, I'm dealing with barcodes that are mostly digits, but have 2 alphabetical characters in them. It doesn't really matter if they're upper or lowercase or not, but it would be nice if they're all uppercase, all the time. So I think I'm okay with the "side-effect" that you describe. But generally speaking, I think I would agree with your assessment. Thanks for the tip. – Pretzel Jul 20 '10 at 15:07

1 Answers1

5

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

tanascius
  • 53,078
  • 22
  • 114
  • 136
  • Thanks for the confirmation! Every reference I had ever read about Auto-Properties had never mentioned anything about this. It seemed implied by how some articles and books were written, but nothing was ever explicitly stated that it was, in fact, this way. Thanks again for confirming my suspicions. – Pretzel Jul 20 '10 at 14:56
  • Looks like my awarding you the "Green check" pushed you up to 10K. Congrats! You can moderate now. :D Please be kind to the rest of us underlings... :O – Pretzel Jul 20 '10 at 15:13
  • @Pretzel: Thanks, you are right, it was your "green check" ^^ that was a long way to go to get this 10K. – tanascius Jul 20 '10 at 15:32