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("'", "''"); }
}
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With