C# and const

When I first started developing programs using C# I had a lot of baggage that I carried over from C++. One of the programming good practices we used to follow in C++ is marking all instance methods (C++ folks insist on calling functions) that do not change the state of an instance as const. To ensure that methods did not accidentally change objects it was not supposed to change the parameters were passed as const as well. Both of these practices are highlighted in the following code

 class MyClass{    int _value;public:    int GetValue() const    {        // the following assignment would have failed to compile        //_value = 5;        return _value;    }    void SetValue(int pVal)    {        _value = pVal;    }}; void show(const MyClass& mc){    // The following line compiles because GetValue is     // marked as const in MyClass    cout << mc.GetValue() << endl;    // the following call would have failed to compile    //mc.SetValue(30);}

In the above code if a maintainer came after a year or two and tried to make any changes in the GetValue method that changed the object it would fail to compile. Similarly if MyClass is in some class library then the const method suffix clearly indicates to the user that the method does not change the object in anyway.

Marking methods with const had an additional benefit as well. In case a methods parameter is marked as const it is not allowed to change the state of the object passed to it. The compiler only allows calls to const methods in this case. However, there are several Gotchas to it, too many for most programmers liking. For example there is nothing to stop a programming from doing the following

 void show(const MyClass& mc){    MyClass& mcNotConst = const_cast<MyClass&>(mc);    mcNotConst.SetValue(20); }

However, I don't think that this is a big issue. Because in a C++ project, the lead's job description includes search for const_cast and fire the guy who sneaked it in. But some gotchas are real bad see https://cpptips.hyperformix.com/cpptips/const_logical

C# unfortunately does not support const methods or const parameters. I always believed that its the duty of a language to be as self-descriptive as possible, const fits well into this even with const_casts lying around.

There is a new feature in C# 2.0 that somewhat helps in a similar scenario. With C#2.0 get and set accessors of a property can be of different accessibility. So you can make the get accessor public and the set protected as follows

 class MyClass{    int _val;    public int Val    {        protectedset { _val = value; }        get { return _val; }    }}