Cook Computing

C# - Const Parameters and Methods

May 22, 2002 Written by Charles Cook

Returning to the subject of the advantages MC++ has over C#, I was writing some unmanaged C++ like this yesterday:

void Foo(const string& str) 

which triggered the realisation that C# doesn't support either const parameters or const methods. Maybe this was something else that could quoted in MC++'s favour? However a test program revealed that although const parameters can be used in the methods of a managed class, methods themselves cannot be defined as const.

Classes with methods using const parameters compile as CLS-compliant, using a modifier to indicate that a parameter is const:

.method public instance void Foo(int32 modopt([Microsoft.VisualC]Microsoft.VisualC.IsConstModifier) i) cil managed

So MC++ does have a slight edge on C# here. It would have been nice if the CLR supported the concept of const methods and parameters. Use of const may not prevent very many bugs but it may encourage a more disciplined approach to writing code.