[.net] A simple question about get/set.... C# .NET

Started by
20 comments, last by Kaze 16 years, 11 months ago
Sorry if this has been suggested already, but...

have you considered writing an interface like

interface ISomeFooReadOnly{    int Value { get; }}


Then you could have the SomeFoo class implement it explicitly, like:
class SomeFoo : ISomeFooReadOnly{    public int Value {get { return _value; } set {_value = value; } }    int ISomeFooReadOnly.Value { get { return Value; }}}

then in your Foo class, have your SomeFOO property have the return type ISomeFooReadOnly. Then you just return it the way you are already doing it.

It's not as elegant a solution as const modifiers in C++, but it allows you to get around the problem by creating a read-only interface to a mutable object... you can't accidentally change what's in the object because you have to explicitly case it to the SomeFoo type to call any set accessors. Plus there's no copying involved.

[Edited by - kanato on May 25, 2007 12:07:24 PM]
Advertisement
if i remember correctly in C# you can still pass a uncloned modifiable reference of a struct to a function, you just have to use the out keyword when passing it to keep it from cloning, i'm not sure if you can store the reference in non-function-parameter variable without cloning it though

This topic is closed to new replies.

Advertisement