Search code examples
c#getter-setter

Expand only setter and use shorthand for getter c#


Is there any way to implement only setter and keep using shorthand (get;) for getter in c# or other way around?

For example: converting email to lower case while setting-

public string Email { get; set { Email = value.ToLower(); } }

Can we do this in any way?


Solution

  • No you can't. The auto property syntax creates a hidden field that you cannot access from code, so you cannot set the field even if the syntax above would be valid, which it is not

    Shortest version using the latest C# would be

    private string _Email     
    public string Email { get => _Email; set => _Email = value.ToLower();  }