Can I Override with derived types?

You can re-declare (new), but you can’t re-declare and override at the same time (with the same name). One option is to use a protected method to hide the detail – this allows both polymorphism and hiding at the same time: public class Father { public Father SomePropertyName { get { return SomePropertyImpl(); } } … Read more

C# Covariance on subclass return types

UPDATE: This answer was written in 2011. After two decades of people proposing return type covariance for C#, it looks like it will finally be implemented; I am rather surprised. See the bottom of https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/ for the announcement; I’m sure details will follow. First off, return type contravariance doesn’t make any sense; I think you … Read more

Is this a covariance bug in C# 4?

Variance only works for reference-types (or there is an identity conversion). It is not known that TBase is reference type, unless you add : class: public void Foo<TBase>() where TBase : class, IBase since I could write a: public struct Evil : IBase {}

How to get around lack of covariance with IReadOnlyDictionary?

You could write your own read-only wrapper for the dictionary, e.g.: public class ReadOnlyDictionaryWrapper<TKey, TValue, TReadOnlyValue> : IReadOnlyDictionary<TKey, TReadOnlyValue> where TValue : TReadOnlyValue { private IDictionary<TKey, TValue> _dictionary; public ReadOnlyDictionaryWrapper(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(“dictionary”); _dictionary = dictionary; } public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } public IEnumerable<TKey> Keys … Read more

Question about C# covariance

Simply put, IList<T> is not covariant, whereas IEnumerable<T> is. Here’s why… Suppose IList<T> was covariant. The code below is clearly not type-safe… but where would you want the error to be? IList<Apple> apples = new List<Apple>(); IList<Fruit> fruitBasket = apples; fruitBasket.Add(new Banana()); // Aargh! Added a Banana to a bunch of Apples! Apple apple = … Read more