Question

What is difference between these two type of property definitions?

First

public class Person   
{ 
   public string FirstName { get; set; } 
   public string LastName { get; set; } 
}

Second

public class Person   
{
  private string firstName;
  private string lastName;

  public string FirstName
  {   
        get { return this.firstName; }  
        set { this.firstName = value;}
  }

  public string LastName
  {   
        get { return this.lastName; }  
        set { this.lastName = value;}
  }
}
Was it helpful?

Solution

The second solution is the same as the first one only that it is more extended.

public class Person   
{ 
   public string FirstName { get; set; } 
   public string LastName { get; set; } 
}

This is the default way of creating a public value, however if you want anything to be done while setting or getting the value you use the second solution, which is the same as the first one but extended.

For instance if you would want to only have names in lowercase you would use the following code:

public class Person   
{
  private string firstName;
  private string lastName;

  public string FirstName
  {   
        get { return this.firstName; }  
        set { this.firstName = value.ToLower();}
  }

  public string LastName
  {   
        get { return this.lastName; }  
        set { this.lastName = value.ToLower();}
  }
}

OTHER TIPS

In some cases you might need to add some additional logic before setting and retreiving the value, in such case the second way that you mentioned will be helpful

like if you want to check the length or assign some session value etc set { ViewState["SomeStr"] = value; }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top