Alex Rivera | Logout

Differences between Private Fields and Private Properties

Asked 2009-01-04T14:26:27.323
41

What is the difference between using Private Properties instead of Private Fields

private String MyValue { get; set; }

// instead of

private String _myValue;

public void DoSomething()
{
   MyValue = "Test";

   // Instead of

   _myValue = "Test";
}

Is there any performance issue ? or just a naming convention ?

Edit
Report

2 Answers

29

Private properties allow you to abstract your internal data so that changes to the internal representation don't need to affect other parts of your implementation, even in the same class. Private fields do not offer this advantage. With automatic properties in C# 3.0, I rarely see a need to implement fields directly -- private or public.

answered 2009-01-04T14:37:09.280
0

When dealing with private access, the differences are very small. Yes, there is a performance hit (which may be optimized by the JIT) send properties represent a method call, instead of a direct address access.

The main advantage to using properties is to allow changing the implementation without changing the external signature required. Since these are privately accessed, any changes to the implementation only effects local code.

When dealing with private members, I see no advantage gained from properties, except for your team's conventions.

answered 2009-01-04T17:02:18.693

Your Answer