views:

151

answers:

4

Hi,

I am just learning C# and I have a problem now. :-) In C++ I loved to use "const reference" as a parameter to avoid that the called method changes my passed object.

I read somewhere that I can do sth. similar in C# by using Interfaces. In the interface I would just put some "getters" to allow the method a readonly access to my object.

Now guess, that I want to pass my C# method a built-in container like "List". But I want to avoid that the method changes something in that list. Just read only!

My first thought was: - I create a new Interface called IMyOwnInterface, which uses the interface IList as well

  • My new interface IMyOwnInterface contains only "getters"

  • I change my method to sth. like that MyLittleMethod(IMyOwnInterface if)

  • Now the method "MyLittleMethod" can just see the "getters", which I put in my own interface and not the "setters" of IList

Is this possible? Can someone give me a hint?

+1  A: 

Yes, I believe that would work. Give it a shot, and let us know how it works :D

McKay
A: 

The answer is no:

IList does not implement IMyOwnInterface so you can't cast it.

IList list = ...
MyLittleMethod((IMyOwnInterface)list)    // Compiler errror here

In this case you can use ReadOnlycollection:

IList list = ...
MyLittleMethod(new ReadOnlyCollection(list))
I use now ReadOnlyCollection for the case of List but Dictionaries?There is no ReadOnly... for Dictionaries, right?
mrbamboo
A: 

With interfaces, it's basically only possible through inheritance or with some proxy stuff (either explicit with an adapter class, via a RealProxy implementation, or with a library to do things like that, such as LinFu).

However, out of the box you can use delegates to do late-binding for single methods with matching signature.

Lucero
Very complicated, especially for a beginner.
+3  A: 

You want to use List.AsReadOnly.

http://msdn.microsoft.com/en-us/library/e78dcd75(VS.80).aspx

McWafflestix
IList has no AsReadOnly method.
@Miriam: If it's an IList<T> in C# 3, you can use list.ToList().AsReadOnly().
TrueWill
You can always do a `IList<T> readOnlyList = new ReadOnlyCollection<T>(mutableList);` which creates an access wrapper for the original list (changes to the original list will be reflected in the readonly list).
Lucero
@Lucero ReadOnlyCollection works just for List but what if I want to use a Dictionary?
mrbamboo
@mrbamboo: http://www.blackwasp.co.uk/ReadOnlyDictionary.aspx. Easily found on Google.
McWafflestix