Blocking access to private member variables? Force use of public properties?

As others have suggested this should be an answer…

You can still use automatic properties in C# 3 when targeting .NET 2.0, along with quite a few other C# 3 features. Unlike (say) expression trees, automatic properties don’t need anything special from the CLR or the framework, beyond the [CompilerGenerated] attribute (which was introduced in .NET 2.0).

So if you’re using VS2008 or VS2010, then it would be worth using an automatic property.

For what it’s worth though, I’d like this ability too. I’d like to be able to scope variables within a property:

 public string Name
 {
     private string name;
     get { return name; }
     set { name = value; }
 }

I view this a bit like making a private variable readonly – it makes no difference to clients, but it helps to enforce correctness within the class code itself.

Leave a Comment