const correctness in C# (CSharp)

One of the first things, what a C++ programmer is missing is the ability of passing objects as const. In good old C++ we used it most of the time to be sure that no one is going to change the passed object.

But what happened in C#? There is no built-in functionality, allowing us to do the same thing.
Anyway, we can use some tricks as a good workaround to reach the C++ feature.

Collections:
Passing of any collection instances can be protected by creating an own proxy for the desired collection type. For this purpose you have to define an interface, which contains only public getters and private setters.
This is an easy way of protecting the passed collection. But this is just the one side of the coin.

“Why?”

This modification protects just the collection but not it’s content. This means: First protect the collection and second protect the object inside the collection.

But how?

Class:
Instead of using the own class directly, define an interface and use this interface in your collection. Like above, the interface must have properties with private setters.

If you need some examples I would recommend you the article of Glenn Dawson.

Advertisement

~ by Ferhat Akgün on 28.February 2010.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.