Thursday, February 21, 2008

Can't change access modifiers when inheriting from Generic Types.

Well I might be silly, but I had not run-up to this one yet. Until just now:
You cannot change the accessibility level of a class member by means of hiding when inheriting from a generic type.
Consider this example. A simple console application using two classes: MyList inherits from List and My2ndList inherits from MyList. Generic type List has a public method named Add that is not declared as virtual.
My intention was to completely hide the base implementation of the Add method in my derived class. In other words, let's assume that I want MyList class to not expose an Add method. What one would normally do in this case, would be to hide the method by using the new modifier and changing its access modifier from public to private like I tried to do in line 32 of the code snippet that follows.
Well. Guess what. This does not work if you are inheriting from a Generic Type. Try the code bellow then try to play around with the access modifiers in lines 32 and 47. Although I would normally assume that the code bellow would not even compile, it does!

So why am I posting about this?

Well... I didn't come across any comments on the subject on the Internet for the little I looked around and I thought it was an interesting thing to talk about.

If you know of any links discussing the subject and explaining the internals of the compiler or generics implementation in C#, then by all means please do leave a comment to this post.