Why wasn't C# designed with 'const' for variables and methods?
- by spoulson
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++;
}
}