Re: Readonly locals?
- From: "Bob Powell [MVP]" <bob@xxxxxxxxxxxxxxxxxxxxxxx>
- Date: Mon, 30 Jun 2008 23:04:52 +0200
You can simulate something like what you want with a property as shown below.
int _p;
bool _pset;
int P
{
get{return _p;}
set
{
if(!_pset)
{
_pset=true;
_p=value;
}
}
}
To expect this of the compiler for a field is, IMO, a nonsense.
A class should have access to its fields but allowing public access to fields breaks the rules of encapsulation so classes must provide properties.
A class should have enough knowledge of it's own internal workings to not break rules that it sets for itself. This implies that the need for such a construct as an immutable or "set-once" local variable is superflouous.
--
--
Bob Powell [MVP]
Visual C#, System.Drawing
Ramuseco Limited .NET consulting
http://www.ramuseco.com
Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm
Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm
All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
"Weeble" <clockworksaint@xxxxxxxxx> wrote in message news:ab783295-30c3-4d90-83f8-9574d195460d@xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
I was surprised to discover today that local variables can't be
"readonly". (They can be "const", but that's only for compile-time
constants, not something that might be calculated at run-time.) I
would have expected such a variable to allow assignment via an
initialiser, but to be readonly for the remainder of the method, i.e.
it would be an error to place it on the left of an assignment or to
use it as an out parameter. This would be useful to let others
maintaining the code know that the value/reference assigned to the
variable at the top of the method won't have changed further down the
method, especially so when the objects involved are immutable. I can
only assume that it's not allowed simply because the feature is not in
high demand? (Certainly, it's nowhere near as important as being able
to have readonly fields, simply because there are so many more places
to search for code that might modify a field.)
I searched this newsgroup for any mention of readonly local variables,
but the only mention was from years ago. Does this mean that nobody
would find such a feature useful? Am I missing some way to get a
similar effect?
.
- References:
- Readonly locals?
- From: Weeble
- Readonly locals?
- Prev by Date: Invalid character returned when reading UTF-8 XML
- Previous by thread: Readonly locals?
- Next by thread: DataGridViewColumns .NET 2.0 by RustemSoft.
- Index(es):
Relevant Pages
|