My project contains a large number of classes with properties whose backing field is marked readonly as they are only set at construction. As a matter of style, I like usin
No, unfortunately there's no way of doing this. Personally there are two things that I think are missing from automatically implemented properties in C# - a default value (which I believe will be in VB10) and readonly properties which can only be set in the constructor. In other words, I'd like to be able to do:
public class Foo
{
public string Tag { get; internal set; } = "Default value";
// The "readonly" would imply "private" as it could only
// be set from a constructor in the same class
public int Value { get; readonly set; }
public Foo()
{
// Valid to set property here, but nowhere else
Value = 20;
}
}
As Jared mentioned, this would mean changing compiler calls to the property setter into simple field assignments, and making sure they only occurred in the constructor.
This would make writing immutable types simpler. Unfortunately the situation won't improve in C# 4. Let's hope we get something like this for C# 5...