On Wed, 01 Oct 2008 11:36:06 -0700, puzzlecracker <ir*********@gmail.com>
wrote:
I'd like to know the standard way to send reference type as const? I
suppose no need for that for value types since they copied anyway.
What if we send value types, not as const, and it contains a
references type as a member. Then reference member will be modified,
hence there is a need to send even value types as const if such
behavior is desired. Now, please tell me how it's done.
As I said, you can't. C# doesn't have the concept of const arguments for
methods. If a reference type is mutable, then any code with a reference
to an instance can theoretically mutate the instance.
"Theoretically" because, of course, you could use member accessibility as
a way of limiting what code can modify the instance, by making any member
of the class that could mutate the instance inaccessible to the code using
the instance. It's not really the same thing as "const" would be, but
depending on your goals, it could work.
Of course, another approach is to design immutable classes. One very
well-known example of an immutable class is the String class. Immutable
types can be inconvenient in some ways, but they offer some surprisingly
powerful promises that can lead to very elegantly safe code. With an
immutable class, any reference to that class is inherently "const".
Note that even in C++, passing an argument as "const" wouldn't cause
mutable members of that argument to also be "const". That is, a reference
member of a class or struct could itself still be modified, even if you
can't change the reference in the passed argument. There might be a
language that supports that sort of thing, but it's not ones I'm most
familiar with. It shouldn't be surprising that C# doesn't include that
feature.
Pete