DEV Community

Discussion on: Start using fields in C#. Using properties is not a good habit and won't do you any good...

Collapse
 
hnicolas profile image
Nicolas Hervé

In your example you use default property setter and getter but you can define your own property accessors for this purpose which is much cleaner.

public class Address
{
    private string _zipCode;

    public string ZipCode
    {
        get => _zipCode;
        set
        {
            // validation
            if (string.IsNullOrEmpty(value))
            {
                throw new Exception("Invalid zip code");
            }
            _zipCode = value;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

docs.microsoft.com/en-us/dotnet/cs...

Collapse
 
lukaszreszke profile image
Łukasz Reszke

Hey Nicolas, you're totally right.
That's another way to do it :) Thanks for sharing!

Collapse
 
hnicolas profile image
Nicolas Hervé

It is the idiomatic way to do it.