Enforce Constness With C#
Unfortunately, C# doesn't have the const keyword. Here's how to fake it by using interfaces.
by Bill Wagner
August 2003 Issue
Technology Toolbox: C#
My single biggest complaint with the C# language is the removal of the const keyword. C++ programmers use this feature to have the compiler ensure that an object isn't modified by a function. For example, this function takes a "const Employee*" as its parameter:
void PrintEmployee (const Employee* e);
Inside the function, you're only allowed to call const methods defined in the Employee class. A const method promises not to modify the object that "this" refers to: /
/ inside employee class:
double GetSalary () const;
// GetSalary does not modify anything.
C# doesn't include this keyword; it's unfortunate because every parameter to a C# function is passed by reference. Any function could easily change any of the objects passed to it. You can fix this by creating a const interface that removes this danger. Follow these three steps to do this with any class.
1. Factor out const methods.
The methods that do not modify the object are the get accessors on the properties (see Listing 1). Every other method can modify the object it refers to. So, the const interface for the Employee class should contain the read-only versions of those properties:
interface IConstEmployee
{
string LastName
{ get; }
string FirstName
{ get; }
int ID
{ get; }
decimal Salary
{ get; }
string DisplayName
{ get; }
}
This separates the const interface of Employee from the non-const interface of Employee.
2. Declare the interface in the original class.
This is simple: Add the new interface to the list of interfaces supported by the original class:
class Employee : IConstEmployee
Now, recompile and you have a class with its own interface that supports its const-interface using an explicit interface declaration (see Listing 2). One final step remains.
Back to top
|