473,657 Members | 2,763 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Mutable Types and Read-Only Fields

http://msdn2.microsoft.com/en-US/lib...57(VS.80).aspx

* Do not assign instances of mutable types to read-only fields.

I would have to disagree with this "Field Design" guidelines...to an extent.

Example:

public class SomeClass {
private NameValueCollec tion mCollection;
public SomeClass() { mCollection = new NameValueCollec tion(); }
public NameValueCollec tion Collection {
get { return mCollection; }
}
public int CollectionCount ()
{
return mCollection.Cou nt;
}
}

For the above (granted, there may be some errors as this is just off top of
my head), the CollectionCount method requires that the mCollection field be
set. I expose the collection to the callee using a read-only property. The
property returns the mutable type just as I want. In a scenerio for my
example, the callee is allowed to change the internal collection values
(add/remove items to a list). But, if the user was allowed to modify the
actual reference, they could set it to null which would cause other areas of
the class (the mCollection.Cou nt) to throw NullReferenceEx ception's.
Therefore, am I not correct that in this instance, the mutable type being
returned by a read-only field is an exception to the rule?

Thanks,
Mythran

Apr 20 '06 #1
3 1575
Why does it need to be read only? Why not just have a get accessor? I
don't think there's any reason to this rule other than the fact that
"readonly mutable type" is misleading. Yes you can't change the
reference but readonly also should imply that you can't change the
value (and thus change things like the return from GetHashCode(), etc).

Apr 20 '06 #2
Hi,

For the above (granted, there may be some errors as this is just off top
of my head), the CollectionCount method requires that the mCollection
field be set. I expose the collection to the callee using a read-only
property.
You expose it using a get property, using this only assure that the
reference holded in the class will not change, on other words, if you are
holding a reference to instance A the callee can not make change it to
instance B. IT DOES NOT assure that the instance itself cannot change its
state. If you want this the referenced class hasve to be inmutable ( like
string).
The property returns the mutable type just as I want. In a scenerio for
my example, the callee is allowed to change the internal collection values
(add/remove items to a list). But, if the user was allowed to modify the
actual reference, they could set it to null which would cause other areas
of the class (the mCollection.Cou nt) to throw NullReferenceEx ception's.
Therefore, am I not correct that in this instance, the mutable type being
returned by a read-only field is an exception to the rule?


I will try to explain, but the language can be confused, feel free to
comment back if further clarification is needed.

A readonly field and a read-only property ( which only define a get ) has
nothing in common. They are two completely different concepts.

a readonly field is declared using the readonly reserved word, this has two
implications:
1- a value should be assign in the spot or in a constructor
2- after it's assigned you cannot change it.

If you assign a primitive type you have effectively blocked that value :

readonly int i=5;

has the effect that i will ALWAYS be 5.

A similar thing happens with a struct:

public struct S
{
public int i;
}

class C
{
readonly S s = new S();

void method1()
{
s.i=4; //error
}

}
Now if the readonly is a referenced type, all the above change.

What you cannot change is the referenced instance, the member of the
instance can be changed at will:

public class S
{
public int i;
}

class C
{
readonly S s = new S();

void method1()
{
s.i=4; //good now
s = new S(); //error
}

}
hope this clarify it.
Let me know if not.

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation


Apr 20 '06 #3
On 2006-04-20, Mythran <ki********@hot mail.comREMOVET RAIL> wrote:
http://msdn2.microsoft.com/en-US/lib...57(VS.80).aspx

* Do not assign instances of mutable types to read-only fields.

I would have to disagree with this "Field Design" guidelines...to an extent.

Example:

public class SomeClass {
private NameValueCollec tion mCollection;
public SomeClass() { mCollection = new NameValueCollec tion(); }
public NameValueCollec tion Collection {
get { return mCollection; }
}
public int CollectionCount ()
{
return mCollection.Cou nt;
}
}
The guidelines you reference are distinguishing between fields and
properties. In the above code, the property is readonly, while the
field is not, which is exactly what the guidelines suggest doing.

For the above (granted, there may be some errors as this is just off top of
my head), the CollectionCount method requires that the mCollection field be
set. I expose the collection to the callee using a read-only property. The
property returns the mutable type just as I want. In a scenerio for my
example, the callee is allowed to change the internal collection values
(add/remove items to a list). But, if the user was allowed to modify the
actual reference, they could set it to null which would cause other areas of
the class (the mCollection.Cou nt) to throw NullReferenceEx ception's.
Therefore, am I not correct that in this instance, the mutable type being
returned by a read-only field is an exception to the rule?

Thanks,
Mythran

Apr 22 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
7391
by: Gordon Airport | last post by:
Has anyone suggested introducing a mutable string type (yes, of course) and distinguishing them from standard strings by the quote type - single or double? As far as I know ' and " are currently interchangeable in all circumstances (as long as they're paired) so there's no overloading to muddy the language. Of course there could be some interesting problems with current code that doesn't make a distinction, but it would be dead easy to fix...
49
2593
by: Mark Hahn | last post by:
As we are addressing the "warts" in Python to be fixed in Prothon, we have come upon the mutable default parameter problem. For those unfamiliar with the problem, it can be seen in this Prothon code sample where newbies expect the two function calls below to both print : def f( list= ): print list.append!(1) f() # prints
3
2356
by: Ingo Nolden | last post by:
Hi, I try to use const where ever appropriate. In a collection class I am counting the iterators that are out. The counter decrements when an iterator leaves scope or is 'Dispose( )'d While iterators are around, any deleted item remains as NULL entry in the inner std::list This way I had to remove const from most of my member functions. Is is
6
1736
by: christopher diggins | last post by:
I wrote a dynamic matrix class similar to the one described in TCPL 3rd Edition. Rather than define two separate iterators for const and non-const scenarios I decided to be a lazy bastard and only have one and make the data representation (a std::valarray) mutable instead. My question is, how bad is that? Am I running the risk of undefined behaviour, or is the worst case scenario simply const violation? -- Christopher Diggins...
13
1603
by: Suresh Jeevanandam | last post by:
# I am new to python. In python all numbers are immutable. This means there is one object ( a region in the memory ) created every time we do an numeric operation. I hope there should have been some good reasons why it was designed this way. But why not have mutable numbers also in the language. A type which would behave as follows: a = MutableInt(12)
12
3742
by: Water Cooler v2 | last post by:
Are JavaScript strings mutable? How're they implemented - 1. char arrays 2. linked lists of char arrays 3. another data structure I see that the + operator is overloaded for the string class and hence it is possible to do: txt += "foo bar";
12
3142
by: Vincent RICHOMME | last post by:
Hi, I am currently implementing some basic classes from .NET into modern C++. And I would like to know if someone would know a non mutable string class.
5
1608
by: Andreas Beyer | last post by:
There has been quite some traffic about mutable and immutable data types on this list. I understand the issues related to mutable numeric data types. However, in my special case I don't see a better solution to the problem. Here is what I am doing: I am using a third party library that is performing basic numerical operations (adding, multiplying, etc.) with objects of unknown type. Of course, the objects must support the numerical...
2
4258
by: subramanian100in | last post by:
I am reading David Musser's "STL Tutorial and Reference Guide" Second Edition. In that book, on pages 68-69, definition has been given that "an iterator can be mutable or constant depending on whether the result of operator* is a reference or a constant reference." As per this definition, on page 71 in this book, it is mentioned that for 'set' and 'multiset', both the iterator and const_iterator types are constant bidirectional types -...
24
2506
by: Steven D'Aprano | last post by:
Sometimes it seems that barely a day goes by without some newbie, or not- so-newbie, getting confused by the behaviour of functions with mutable default arguments. No sooner does one thread finally, and painfully, fade away than another one starts up. I suggest that Python should raise warnings.RuntimeWarning (or similar?) when a function is defined with a default argument consisting of a list, dict or set. (This is not meant as an...
0
8394
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8825
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6164
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1615
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.