How 'read-only' are read-only properties?

  • Thread starter Thread starter Rakesh
  • Start date Start date
R

Rakesh

Hi,

Suppose I have a class definition like this:
public class CBase
{
public string m_Name = "asd";

public string Name
{
get
{
return m_Name;
}
}
}

Even though 'Name' is a read-ionly property, I can do this:
CBase c1 = new CBase();
c1.Name.Remove(0, 2);

So what's the point is declaring a get-only property?

Thanks,
Rakesh
 
Hi Rakesh,

You can't change the string instance.
You can modify its content, yes, since string is treated as a class and
readonly properties (as you've stated) don't prevent changing instance
fields.

In the case of simple types like int, bool, etc. it works as one would
thought :)
 
It's read only.

cl.Name.Remove(0,2) doesn't change m_Name in any way, it just returns a
new string.
Though you should make m_Name private or anyone could bypass Name and
handle m_Name directly instead.
 
Hi,
Read-only in this context means you can't assign to this
property (as no setter method is provided). It doesn't
mean that the returned reference (by the getter) can't be
changed. Doesn't work for value classes of course.
BTW, the Remove method actually creates a new instance of
type String reflecting the change, while the original
string remains unaffected. This happens to be so for all
the other methods, which make it immutable.
Regard,
BV
 
You can't change the string instance.
You can modify its content, yes, since string is treated as a class and
readonly properties (as you've stated) don't prevent changing instance
fields.

Well, you *would* be able to, if string weren't immutable.

If Name returned a StringBuilder rather than a string, that would
certainly allow modification.
 
Hi Miha,

So do u mean that we can change the value of read-only
properties exposing objects(not primitive types), but
cannot assign values to them?

Rakesh
 
Hi rakesh,

An example:

public class Tubo
{
public int Value = 0;
}

public class Tubular
{
private Tubo tubo = new Tubo();

public Tubo Tubo
{
get { return tubo; }
}
}

Tubular t = new Tubular();

you are allowed to:
t.Tubo.Value = 5; // changing the internal value of Tubo

while you won't be able to:
t.Tubo = null;
or
t.Tubo = new Tubo();
since you are trying to write the new t.Tubo property value.

HTH,
 
Even though, of course 'read-only' is meant to mean exactly that. One can work-around this fact by eithe
locking the member or class

Thought it would help
Chop

----- Miha Markic wrote: ----

Hi rakesh

An example

public class Tub

public int Value = 0


public class Tubula

private Tubo tubo = new Tubo()

public Tubo Tub

get { return tubo;



Tubular t = new Tubular()

you are allowed to
t.Tubo.Value = 5; // changing the internal value of Tub

while you won't be able to
t.Tubo = null
o
t.Tubo = new Tubo()
since you are trying to write the new t.Tubo property value

HTH
 
Back
Top