C # properties: how to use a custom set property without a private field?

I want to do this:

public Name { get; set { dosomething(); ??? = value } } 

Can I use an automatically generated private field?
Or it is required that I implement it as follows:

 private string name; public string Name { get { return name; } set { dosomething(); name = value } } 
+71
c # properties
Jan 28 2018-11-23T00:
source share
5 answers

Once you want to do something custom in a getter or setter, you can no longer use the auto properties.

+85
Jan 28 '11 at 10:27
source share

You can try something like this:

 public string Name { get; private set; } public void SetName(string value) { DoSomething(); this.Name = value; } 
+25
Sep 17 '13 at 16:34 on
source share

It's impossible. Automatically implemented properties or custom code.

+14
Jan 28 '11 at 10:25
source share

It is required that you fully implement it according to your scenario. Both get and set should either be automatically implemented, or fully implemented together, and not a combination of the two.

+5
Jan 28 '11 at 10:27
source share

Starting in C # 7, you can use expression body definitions for the get and set accessors properties.

More here

 private string _name; public string Name { get => _name; set { DoSomething(); _name = value; } } 
+2
Feb 13 '19 at 9:53
source share



All Articles