Why wasn't C# designed with 'const' for variables and methods?

Posted by spoulson on Stack Overflow See other posts from Stack Overflow or by spoulson
Published on 2010-06-03T17:12:13Z Indexed on 2010/06/03 17:14 UTC
Read the original article Hit count: 215

Filed under:
|

I suspect const was simplified for the C# spec for general language simplicity. Was there a specific reason we can't declare variable references or methods as const like we can with C++? e.g.:

const MyObject o = new MyObject();  // Want const cast referenece of MyObject
o.SomeMethod();    // Theoretically legal because SomeMethod is const
o.ChangeStuff();   // Theoretically illegal because ChangeStuff is not const

class MyObject {
   public int val = 0;

   public void SomeMethod() const {
      // Do stuff, but can't mutate due to const declaration.
   }

   public void ChangeStuff() {
      // Code mutates this instance.  Can't call with const reference.
      val++;
   }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about const