Alex Rivera | Logout

Where are the readonly/const in .NET?

Asked 2010-05-11T20:36:01.033
30

In C++ you'll see void func(const T& t) everywhere. However, i havent seen anything similar in .NET. Why?

I have notice a nice amount of parameters using struct. But i see no functions with readonly/const. In fact now that i tried it i couldnt use those keywords to make a function that promises to not modify a list being passed in. Is there no way to promise the caller that this function will never modify the contents of list? Is there no way to say to call code and say this list should never be modified? (I know i can clone the list or look at documentation but i like compile errors sometime)

Edit
Report

1 Answer

7

There is no const modifier for method parameters in C#. If you want to have something similar to const guarantees you can use immutable types in your interfaces. For example, a method can accept an IEnumerable<T> instead of a mutable collection type. You can also look at ReadOnlyCollection.

answered 2010-05-11T20:39:07.013

Your Answer