Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between encapsulating a private member as a property and defining a property without a private member?

What's the difference (Performance, memory...etc) between encapsulating a private member like this

private int age;
public int Age
{
  get { return age; }
  set { age = value; }
}

and define a property like this

public int Age
{
  get ;
  set ;
}
like image 219
Rami Alshareef Avatar asked Nov 24 '10 13:11

Rami Alshareef


People also ask

Can we have private property in C#?

Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers.

What is the difference between variable and property in C#?

In C# any "variable" that has a getter and setter is referred to as a property. A variable has no getters and setters or so that is what the text books say. My programming instructor made us have getters and setters for almost every variable that we created in Java.

What is an Auto property C#?

What is automatic property? Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it.

What does get set do?

The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.


1 Answers

In the second case, the C# compiler will generate a field for you and generate a getter and setter to access it. In other words, there is no functional difference between the two code samples you posted. The only difference will be the name of the private field, which will be compiler-generated.

like image 180
cdhowie Avatar answered Oct 20 '22 08:10

cdhowie