Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a correct way to use auto-implemented properties in C#

I want to assign some default value to a property or want to replace some character like given below. Is it a 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("'", "''"); } 
        }
like image 485
Shantanu Gupta Avatar asked Nov 29 '22 05:11

Shantanu Gupta


2 Answers

By accessing Login_Name the get will return Login_Name again leaving you with an infinite loop (StackOverflowException).

You should 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 meant to use an auto-implemented property, it would look like this:

public string Login_Name {get;set;}

But auto-implemented properties cannot have any additional logic applied to their gets or sets.

like image 121
djdd87 Avatar answered Dec 05 '22 05:12

djdd87


That won't work; you'd effectively be creating an infinite loop.

Use a separate private field instead:

private string m_loginName;

public string Login_Name 
{ 
    get 
    { 
        return m_loginName; 
    } 
    set 
    {
       m_loginName = !string.IsNullOrEmpty(value) ? value.Replace("'", "''") : value;
    } 
}
like image 45
Warren Rumak Avatar answered Dec 05 '22 06:12

Warren Rumak