3

Possible Duplicate:
Why const parameters are not allowed in C#

I am a C++ developer and I had some experience using C#.

I have always wondered why there is nothing like this in C#:

bool MyFunction(const AnotherClass& x)
{
  //some stuff
}

I personally think that the constness is one of the best features in C++ (it helps the developer to increase encapsulation and decoupling). One of the suggestion of Sutter (C++ Coding Standards: 101 Rules, Guidelines, and Best Practices) is never return your handlers, if I cannot pass by const reference I am giving away the entire class not just the handlers.

Is it my lack of knowledge on C#? There is anything like that in C#? If not, why is C# not using it?

Community
  • 1
  • 1
Alessandro Teruzzi
  • 3,918
  • 1
  • 27
  • 41
  • What does const correctness have to do with either encapsulation or decoupling? – Mud Dec 16 '10 at 16:03
  • I'm not a C++ expert, but isn't that just `bool MyFunction(AnotherClass x)` in C#? – SWeko Dec 16 '10 at 16:05
  • 3
    "Why ..." because C# is a limited language that tries to be simpler at the cost of flexibility and maintainability. – Yakov Galka Dec 16 '10 at 16:05
  • 3
    I can't grasp the ignorance in that statement. – Femaref Dec 16 '10 at 16:07
  • 3
    @ybungalobill - that is FUD; see the linked duplicate for *why* - in particular, note that it is broken in C/C++. why repeat something that is known to be broken? – Marc Gravell Dec 16 '10 at 16:07
  • @SWeko: No, that C# is equivilent to `bool MyFunction(AnotherClass& x)` in C++ - there's no way to duplicate const references in C#. The closest you could get would be `bool MyFunction(AnotherStruct x)` – JoeG Dec 21 '10 at 09:45
  • 1
    @Marc Gravell: what do you mean with "broken"? If someone declare a function const and than inside cast away the costness he/she is just a very bad developer. It is not a lack in the functionality. For example, if I throw the wrong exception is the whole exception mechanism broken or just my bad? – Alessandro Teruzzi Dec 29 '10 at 10:31

1 Answers1

3

That functionality is not available in C#. You can pass a copy, you can wrap the object in a read only adapter, or you can pass references to immutable objects/structures.

THE DOCTOR
  • 4,399
  • 10
  • 43
  • 64