read-only object retrieved from other object?

H

Hyun-jik Bae

Is there any way to prohibit writing values to an object A retrieved from
another object B if B gives A for read only purpose?

For example,

public class B
{
public int xx;
}

public class A
{
public B aa=new B();
public B a
{
get
{
return aa;
}
}
}

class Program
{
static void Main(string[] args)
{
A q = new A();
int w=q.a.xx;
q.a.xx = 3; // STATEMENT X
}
}

where I want STATEMENT X be prohibited.

Please reply. Thanks in advance.
Hyun-jik Bae
 
N

Nicholas Paldino [.NET/C# MVP]

Hyun-jik Bae,

It's not up to B to decide what on A is read only or not. The
implementation of A would have to decide whether or not it allows values to
be changed on it. You might want to have B set a flag on A to indicate it
should be read only (assuming you have control over the definition of A).

If you don't have control over the definition of A, then you could
always return a copy of A from B, in which case, any changes that are made
won't make a difference.

Hope this helps.
 
J

Jon Skeet [C# MVP]

Hyun-jik Bae said:
Is there any way to prohibit writing values to an object A retrieved from
another object B if B gives A for read only purpose?

Unfortunately not. (I disagree with Nick on this front - I think there
are plenty of times when it would be useful to return something in a
read-only way.)

C++ has the idea of "const-correctness" and it's been put forward many
times both for .NET and Java. The main difficulties as I understand
them are:

1) Making the syntax simple but expressive. For instance, if I return
an array of Foo, you might want to declare that the receiver can't
change the contents of the array, or can't change the Foo instances
referred to by the array, or both. We've seen how generics can make for
some pretty long type declarations - const correctness would do the
same kind of thing.

2) Unless it's supported by the standard libraries, it's not nearly as
much use - and making the standard libraries const-correct in
retrospect would quite possibly break a lot of things.


Now admittedly, your example code isn't ideal: B.xx would usually be
exposed as a property instead of a public field, and the property could
be read-only, but I assume in real life other uses of B would need it
to be writable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top