Getter and Setter not working

I currently have the following class with getters and setters

public class CustAccount
{
    public string Account { get; set; }        private string account;
    public string AccountType { get; set; }    private string accountType;

    public CustSTIOrder(Account ord)
    {
        account = ord.Account;
        accountType = ord.AccountType;
    }
}

      

Now I understand that when public string Account { get; set; }

I do not need to declare private string account

. Anyway, now my personal variable account

contains the value, but when I use account

to get the value, I get null. Any suggestions on why I am getting null?

+3


source to share


4 answers


Since you are using the auto property, you must use Account

for all property references.

If you want to use a background field, you need to have a backing ( Account

) field in get

and set

.

Example:



public string Account 
{ 
    get { return account; }
    set { account = value; }
}        
private string account;

      

An example of using the auto property:

public CustSTIOrder(Account ord)
{
    Account = ord.Account;
    // the rest
}

      

+6


source


The private field must be used in the property, otherwise you will get an auto-implemented property that has a different store.



public class CustAccount
{
    private string account;
    public string Account { get {return account;} set{account = value;} }        
    private string accountType;
    public string AccountType { get{return accountType;} set{accountType = value;} }  

    public CustSTIOrder(Account ord)
    {
        account = ord.Account;
        accountType = ord.AccountType;
    }
}

      

+4


source


You need to connect a property Account

with a field Account

:

private string account;
public string Account
{
   get {return this.account;}
   set {this.account = value;}
}

      

+3


source


Just don't use account

, use the property directly:

public class CustAccount
{
    public string Account { get; set; }        
    public string AccountType { get; set; }

    public CustSTIOrder(Account ord)
    {
        Account = ord.Account;
        AccountType = ord.AccountType;
    }
}

      

These auto-properties are internally supported by the field, so you don't need to write this trivial code.

+2


source







All Articles