C#: how to efficiently introduce "Immutable by default" to C#? Immutable attribute?
Reading F# and C# these days, one of the big difference is, F# variants are by default Immutable, most C# reference types are by default mutable.
This brings开发者_开发百科 to a question, how to efficiently introduce this "Immutable as by default" to C# coding? er... i mean C# 4.0..
What came to my mind is an "Immutable Attribute". So when this is docked to a class, by Aspect, each and every member of the class is checked, so that they are only mutable in constructors.
How do you think?
The readonly
keyword is a language-level construct to perform the very action you're requesting. When applied to member variables, they can only be set in the constructor and must be set in the constructor.
I'm not familiar with F#, but C# does have a readonly keyword that can only be applied to members that are initialized at object creation:
public class MyExample
{
private readonly IDependency _dependency;
public MyExample(IDependency dependency)
{
_dependency = dependency;
}
public IDependency Dependency
{
get { return _dependency; }
}
}
The keyword can only be applied to members that are immutable, meaning there's no mechanism to alter them from outside the class.
I'm not entirely sure what you're trying to accomplish -- whether you're suggesting a new feature for C# or if you're asking how to implement forcing private variables to be immutable except during construction.
If it's the latter, you could accomplish that by making your private variables readonly
when you declare them. You can't make every variable you declare "read only" by default, so you'll always have to specify this keyword, but with a bit of discipline when writing new code, it'd get the job done.
One more thing to note: a variable being immutable isn't the same as the object it points to being immutable.
For example,
public class MyClass
{
private readonly List<string> myList;
public MyClass()
{
myList = new List<string>(); // okay
}
public void DoStuff()
{
myList = new List<string>(); // not okay; myList is readonly!
myList.Add("this will work"); // okay -- the list itself is still mutable
}
}
精彩评论