Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

constants

Possible Duplicate:
“const correctness” in C#

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++;
   }
}
like image 666
spoulson Avatar asked Jun 03 '10 17:06

spoulson


1 Answers

A const performs a compile time substitution of the value wherever it is used and therefore doesn't have any runtime meaning. In general what you propose for const objects would be very difficult for the compiler to determine (if a method will modify the object or not). Your proposal to use a const keyword as an access modifier also then puts burden on the writer and you are still left with a problem of verifying of something does or does not modify the object. Also you are imposing something on the object that does not have a meaning in all contexts. What does it mean if the method is const but you aren't using it as a const object? The functionality you want is usually accomplished by implementing an interface and only exposing the "read-only" parts of the class.

like image 68
Craig Suchanec Avatar answered Sep 30 '22 16:09

Craig Suchanec