Re: Making C# properties act like member variables
- From: "Daniel O'Connell [C# MVP]" <onyxkirx@xxxxxxxxxxxxxxxxxxxxx>
- Date: Tue, 26 Jul 2005 00:57:09 -0500
> Is there a decent way within the language to deal with this? I've been
> pondering some solutions myself, but I don't really like any of them so
> far. If C# had the notion of const like C++, I could make get accessors
> return const objects so that I wouldn't have to worry about the client
> code trying to change the object. I considered making every property get
> return a temporary, but then properties have the same syntax as member
> variables but act very definitely. I've also considered returning some
> sort of proxy object that exposes a ByteRgba interface but internally
> holds a reference to the FloatRgba version of diffuseColor and can modify
> that object when it changes, but I think that would require fairly
> extensive changes to both ByteRbga and FloatRbga, and that change may be
> very difficult if we were dealing with more complex types.
>
> In fact, thinking about the whole issue again, I don't think that the
> problem is limited to properties - it would happen with a
> getDiffuseColor() routine as well. Am I missing something obvious?
Well, your mistake is to create a mutable type and have a property return a
temporary copy of it. That will almost always cause a mess, since your
property and the type are at odds(they type says "yes I'm modifiable" but
the property is written in such a way as to asusme that the type won't be
modified). I would personally modify Invert and your other methods so that
it returns a new FloatRbga and change FloatRbga so that it is immutable.
This is a pretty common pattern in the .NET world, System.String is a good
example. You might also consider adding Invert support a level up so that
your clients won't have to use the properties.
Const is a bandaid over the issue, in that it stops users from modifying an
object that was clearly designed to be modified. It reduces the concerns you
ahve, but it would be inconsistent, IMHO, to tell a client they can't modify
a given class right now, but can some place else. The problem here is really
that you are writing C++ code in C#, which just doesn't work, there is no
const, so you have to think about modifiability when designing the type not
the interfaces that use it. Given time you'll start thinking more along the
lines of the language and probably have fewer problems like this.
.
- Follow-Ups:
- Re: Making C# properties act like member variables
- From: Larry Lard
- Re: Making C# properties act like member variables
- References:
- Making C# properties act like member variables
- From: Jeff Grills
- Making C# properties act like member variables
- Prev by Date: Assembly
- Next by Date: Re: Pointer to a generic Class
- Previous by thread: Re: Making C# properties act like member variables
- Next by thread: Re: Making C# properties act like member variables
- Index(es):
Relevant Pages
|