Are these 2 pieces of code the same?

Snippets:

 private double memberVal;   
 public double MemberVal   
 {   
  get { return memberVal; }   
  set { memberVal= value; }   
 }

      

and

public double MemberVal   
 {    
  get; set;  
 }

      

+2


a source to share


4 answers


No, but now they are the same

private double memberVal;
public double MemberVal
{
    get { return memberVal; }
    set { memberVal= value; }
} 

      

and



public double MemberVal
{
get; set;
}

      

Update Also, as Johannes Rössel pointed out, you can access the field from code in the first case, but not in the last :-) -

Assuming that in the first code example inside your class, you can directly set the backing element for the property (i.e. private double memberVal1

eg memberVal = 1.1;

), where in the second, there is still a private backing element for the property, but this is now invisible. You can only access it through a property.

+5


a source


Nearly. In the second example, MemberVal

it is not public.



+13


a source


Yes, this code is equivalent, except that MemberVal is not public in the second example (you meant that). In the latter case, the compiler creates a field for you. It will have a different autogenerated name.

+3


a source


private double memberVal;
public double MemberVal
{
    get { return memberVal; }
    set { memberVal= value; }
} 

public double MemberVal
{
    get; set;
}

      

the second code snippet is not supposed to work with .net 2.0, but it was introduced in .net 3.0.

The second is a short notation for the first, but only works on .net 3.0 or higher.

0


a source







All Articles