This is the right way to use automatically implemented properties in C #

I want to assign a default value for a property or replace any character as follows. Is this the correct syntax, or should I do this by creating a variable.

public string Login_Name { get { return this.Login_Name; } set { this.Login_Name = value.Replace("'", "''"); } } 
+4
source share
6 answers

Upon receiving Login_Name , get will again return Login_Name , leaving you with an infinite loop ( StackOverflowException ).

You must use properties to get and set private members:

 public string Login_Name { get { return _login_Name; } set { _login_Name = value; if (!string.IsNullOrEmpty(_login_Name)) { _login_Name = _login_Name.Replace("'", "''"); } } } private string _login_Name; 

If you want to use the automatically implemented property, it will look like this:

 public string Login_Name {get;set;} 

But automatically implemented properties cannot have any additional logic applied to their sets or sets.

+13
source

This will not work; you actually created an endless loop.

Use a separate personal field instead:

 private string m_loginName; public string Login_Name { get { return m_loginName; } set { m_loginName = !string.IsNullOrEmpty(value) ? value.Replace("'", "''") : value; } } 
+4
source

What you wrote is not an automatically implemented property. A property automatically implemented will look like this:

  public string Login_Name { get; set; } 

Here is a quote from MSDN, my emphasis is:

In C # 3.0 and later, automatically implemented properties make property declarations more concise when additional logic is not needed in property accessories .

When you have additional logic, as in your example, you cannot use a property that is implemented automatically. You can use the usual property and declare a support field yourself.

  private string loginName; public string LoginName { get { return loginName; } set { loginName = (value == null) ? null : value.Replace("'", "''"); } } 
+3
source

I do it like this.

 private string _Login_Name = "Some Default"; public string Login_Name { get { return _Login_Name; } set { _Login_Name = value.Replace("'", "''"); //might want to check for null first } } 
+2
source

You will need to set a variable, otherwise you will end up with infinite recursion and stack overflow. With what you have, your setter calls itself:

 this.Login_Name = ... 

This is the same as your getter calling itself:

 return this.Login_Name; 
+1
source

It is right. The only problem in the fragment provided is the recursive call to the setter method of the property.

 set { this.Login_Name = value.Replace("'", "''"); } 

you must set the value for some private field, and not recursively for the property itself, for example:

 set { loginName = value.Replace("'", "''"); } 
-1
source

Source: https://habr.com/ru/post/1313736/


All Articles