InvalidCastException on Generics - c#

Coming from the Java world, programming with generics and C# is often a headache. Like this one:
interface ISomeObject { }
class SomeObjectA : ISomeObject { }
class SomeObjectB : ISomeObject { }
interface ISomething<T> where T : ISomeObject
{
T GetObject();
}
class SomethingA : ISomething<SomeObjectA>
{
public SomeObjectA GetObject() { return new SomeObjectA(); }
}
class SomethingB : ISomething<SomeObjectB>
{
public SomeObjectB GetObject() { return new SomeObjectB(); }
}
class SomeContainer
{
private ISomething<ISomeObject> Something;
public void SetSomething<T>(ISomething<T> s) where T : ISomeObject
{
Something = (ISomething<ISomeObject>)s;
}
}
class TestContainerSomething
{
static public void Test()
{
SomeContainer Container = new SomeContainer();
Container.SetSomething<SomeObjectA>(new SomethingA());
}
}
Which results into an InvalidCastException at Something = (ISomething<ISomeObject>)s;. In Java, this would work, and I could even use (if all else fails) the generics wildcard <?>. This is not possible in C#.
While this is just an example that I put together to explain the problematic, how can this exception be eliminated? The only main constraint is that SomeContainer cannot be a generic class
** Note ** : there are many questions about this, but none of them (that I could find) address a generic class member inside a non generic class.
** Update **
Inside the method SetSomething, I added these lines :
Console.WriteLine(s.GetType().IsSubclassOf(typeof(ISomething<SomeObjectA>)));
Console.WriteLine(s.GetType().ToString() + " : " + s.GetType().BaseType.ToString());
foreach (var i in s.GetType().GetInterfaces())
{
Console.WriteLine(i.ToString());
}
which to my surprise output
False
SomeThingA : System.Object
ISomething`1[SomeObjectA]
Is this why I get this exception?

Out keyword will be a fix, if your ISomething only have methods that return T
interface ISomething<out T> where T : ISomeObject
when creating a generic interface, you can specify whether there is an implicit conversion between interface instances that have different type arguments.
It is called Covariance and Contravariance
Eric Lippert have a good series of articles why we need to think about this, here interface variance is used
Here is my code, which works as expected for me
interface ISomeObject { }
class SomeObjectA : ISomeObject { }
class SomeObjectB : ISomeObject { }
interface ISomething<out T> where T : ISomeObject
{
T GetObject();
}
class SomethingA : ISomething<SomeObjectA>
{
public SomeObjectA GetObject() { return new SomeObjectA(); }
}
class SomethingB : ISomething<SomeObjectB>
{
public SomeObjectB GetObject() { return new SomeObjectB(); }
}
class SomeContainer
{
private ISomething<ISomeObject> Something;
public void SetSomething<T>(ISomething<T> s) where T : ISomeObject
{
Something = (ISomething<ISomeObject>)s;
}
}
class TestContainerSomething
{
static public void Test()
{
SomeContainer Container = new SomeContainer();
Container.SetSomething<SomeObjectA>(new SomethingA());
}
}

Sometimes it is useful to let a generic interface implement a non generic one to circumvent the missing <?>
interface ISomething
{
object GetObject();
}
interface ISomething<T> : ISomething
where T : ISomeObject
{
T GetObject();
}
public class SomeImplementation<T> : ISomething<T>
{
public T GetObject()
{
...
}
object ISomething.GetObject()
{
return this.GetObject(); // Calls non generic version
}
}
A collection can then be typed with the non generic interface
var list = new List<ISomething>();
list.Add(new SomeImplementation<string>());
list.Add(new SomeImplementation<int>());

Related

Generic interface and covariance - fighting the InvalidCastException

This is probably a classic covariance/contravariance question, it looks like it should work but I'm probably missing a trick.
I'm attempting to return a less derived type from a factory method, but I find that I cannot cast the more specialized concrete instance to a less derived base type.
public class AnimalSettings { ... }
public class CatSettings : AnimalSettings { ... }
public interface IAnimalService<TSettings> { ... }
public abstract AnimalService<TSettings> : IAnimalService<TSettings> where TSettings : AnimalSettings { ... }
public class CatService : AnimalService<CatSettings> { ... }
Then, in a factory method I have:
public static IAnimalService<AnimalSettings> GetAnimalService(AnimalType selector)
{
switch (selector)
{
case AnimalType.Cat:
return (IAnimalService<AnimalSettings>) new CatService();
break;
}
}
and the intention is to be able to do the following:
var service = MyServiceFactory.GetAnimalService(AnimalType.Cat);
service.DoAnimalBehavior();
This compiles fine, but at runtime my code is failing in the attempted cast return (IAnimalService<AnimalSettings>) new CatService();, with an InvalidCastException.
How should I be casting my more derived type to a less derived type so that callers can use that interfaced base type to invoke functionality?
Changing the cast to (IAnimalservice<CatSettings>) new CatService() does work, but it's intended that the caller receives a IAnimalservice<AnimalSettings> so that it can handle any sort of animal (In other words, the caller should not be using any of the more specialized types). Should I be specifying an in or out as part of the generic definition somewhere?
By giving a complete example it would be much easier to help. ;-)
So here is the working code. And as Sweeper already mentioned, you need to add the out parameter at the interface to make it work.
using System;
public class Program
{
public static void Main()
{
var catService = new CatService(new CatSettings());
var genericService = (IAnimalService<AnimalSettings>)catService;
genericService.DoAnimalBehavior();
}
}
public abstract class AnimalSettings
{
public abstract void DoAnimalBehavior();
}
public class CatSettings : AnimalSettings
{
public override void DoAnimalBehavior()
{
Console.WriteLine("Meeoh");
}
}
public interface IAnimalService<out TSettings>
{
void DoAnimalBehavior();
}
public abstract class AnimalService<TSettings> : IAnimalService<TSettings> where TSettings : AnimalSettings
{
private readonly TSettings _settings;
public AnimalService(TSettings settings)
{
_settings = settings;
}
public void DoAnimalBehavior()
{
_settings.DoAnimalBehavior();
}
}
public class CatService : AnimalService<CatSettings>
{
private readonly CatSettings _catSettings;
public CatService(CatSettings catSettings)
: base(catSettings)
{
_catSettings = catSettings;
}
}

Inherited Generic Type Unification

For a scenario such as this:
public interface IAnimal
{
}
public interface IGiraffe : IAnimal
{
}
public interface IQuestionableCollection : IEnumerable<IAnimal>
{
void SomeAction();
}
public interface IQuestionableCollection<out T> : IQuestionableCollection, IEnumerable<T>
where T : IAnimal
{
}
public class QuestionableCollection<T> : IQuestionableCollection<T>
where T:IAnimal
{
// Implementation...
}
The complier will generate an error:
'IQuestionableCollection<T>' cannot implement both 'System.Collections.Generic.IEnumerable<IAnimal>' and 'System.Collections.Generic.IEnumerable<T>' because they may unify for some type parameter substitutions
And that makes sense, there is indeed an ambiguity between the two interfaces which C# can't resolve unless it uses the type constraint, which it doesn't per the language spec as #ericlippert explains here.
My question is how should I implement something to the same effect here?
It seems like I should be able to express that the collection is enumerable for the base interface. (I'd like to provide a set of methods that could be utilized without knowing the concrete type, as well as it make some APIs/reflection code cleaner, so I'd like to keep the base collection as non-generic if at all possible. Otherwise, there would be no need for two interfaces.)
The only implementation I can think of that compiles is something like:
public interface IQuestionableCollectionBase
{
void SomeAction();
}
public interface IQuestionableCollection : IQuestionableCollectionBase, IEnumerable<IAnimal>
{
}
public interface IQuestionableCollection<out T> : IQuestionableCollectionBase, IEnumerable<T>
where T : IAnimal
{
}
public class QuestionableCollectionBase<T> : IQuestionableCollection
where T : IAnimal
{
protected List<T> _items = new List<T>();
public void SomeAction() { }
IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); }
IEnumerator<IAnimal> IEnumerable<IAnimal>.GetEnumerator() { return ((IEnumerable<IAnimal>)_items).GetEnumerator(); }
}
public class QuestionableCollection<T> : QuestionableCollectionBase<T>, IQuestionableCollection<T>
where T : IAnimal
{
public IEnumerator<T> GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); }
}
Note that I've had to move any methods I'd like to use on both interfaces to a base method and have two levels of implementation for the class itself - which seems like I'm jumping through enough hoops here that I've got to be missing something...
How should this be implemented?
The simplest workaround is to change the IEnumerables from "is-a" to "has-a", like this:
public interface IAnimal { }
public interface IGiraffe : IAnimal { }
public interface IQuestionableCollection
{
IEnumerable<IAnimal> Animals { get; }
void SomeAction();
}
public interface IQuestionableCollection<out T> : IQuestionableCollection
where T : IAnimal
{
new IEnumerable<T> Animals { get; }
}
public class QuestionableCollection<T> : IQuestionableCollection<T>
where T : IAnimal, new()
{
private readonly List<T> list = new List<T>();
public IEnumerable<T> Animals
{
get { return list; }
}
IEnumerable<IAnimal> IQuestionableCollection.Animals
{
get { return (IEnumerable<IAnimal>)list; }
}
public void SomeAction()
{
list.Add(new T());
}
}
class Giraffe : IGiraffe { }
[TestMethod]
public void test()
{
var c = new QuestionableCollection<Giraffe>();
IQuestionableCollection<Giraffe> i = c;
IQuestionableCollection<IGiraffe> i2 = i;
Assert.AreEqual(0, c.Animals.Count());
Assert.AreEqual(0, i.Animals.Count());
c.SomeAction();
i.SomeAction();
Assert.AreEqual(2, c.Animals.Count());
Assert.AreEqual(2, i.Animals.Count());
}
Note that you can avoid the cast in QuestionableCollection<T> if you add a where T : class constraint.
Changing IQuestionableCollection to a non-generic IEnumerable sorts the compiler issues.
public interface IQuestionableCollection : IEnumerable {...}
I've seen MS use this pattern in their collections, with the non-generic versions using IEnumerable, and the generic ones using IEnumerable<T>.
Alternatively, making the others IEnumerable<IAnimal> also stops the compiler errors, though it means you get IAnimals back instead of T's when enumerating.
You could try this:
public interface IAnimal
{
}
public interface IGiraffe : IAnimal
{
}
public interface IQuestionableCollection<T> : IEnumerable<T> where T : IAnimal
{
void SomeAction();
}
public interface IQuestionableCollection : IQuestionableCollection<IAnimal>
{
}
public class QuestionableCollection<T> : IQuestionableCollection<T>, IEnumerable<T>
where T : IAnimal
{
public void SomeAction() { }
public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
Given the constraints of the language you won't be able to work around the problem of having IQuestionableCollection and IQuestionableCollection both implementing a Generic Interface.
In essence what you are specifying is that IQuestionableCollection implements two possible lists, List and another List. There is no hierarchical relationship here so it impossible to resolve.
That being said you would have to replace IEnumerable with IEnumerable on IQuestionableCollection to provide an inheritance chain to the compiler. In reality there isn't really even a point to declaring the base IQuestionableCollection unless you plan on implementing a vanilla QuestionableCollection
In my updated code I took it out to a consumer of QuestionableCollection to illustrate the enumeration of QuestionableCollection() retains the typing of IGiraffe.
public interface IAnimal {}
public interface IGiraffe : IAnimal { }
public interface IQuestionableCollection : IEnumerable
{
void SomeAction();
}
public interface IQuestionableCollection<out T> : IQuestionableCollection, IEnumerable<T>
where T : IAnimal
{ }
public class QuestionableCollection<T> : IQuestionableCollection<T>
where T : IAnimal
{
private List<T> list = new List<T>();
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void SomeAction()
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
var questionable = new QuestionableCollection<IGiraffe>();
foreach (IGiraffe giraffe in questionable)
{
}
}
}
For the Non Generic Implementation
1 You can always safely upcast
var questionable = new QuestionableCollection();
IEnumerabl<IAnimal> animals = questionable.OfType<IAnimal>();
-or-
2 You can have the NonGeneric QuestionableCollection class implement IEnumerable
public class QuestionableCollection : IQuestionableCollection, IEnumerable<IAnimal>
{
public IEnumerator<IAnimal> GetEnumerator()
{
var l = new List<Giraffe>();
l.Add(new Giraffe());
l.Add(new Giraffe());
return l.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void SomeAction()
{
throw new NotImplementedException();
}
}
Which you then can enumerate without a cast operation.
var questionable = new QuestionableCollection();
foreach (IAnimal giraffe in questionable)
{
var i = giraffe;
}

Genric object return from Interface

Can somebody help me to get a generic object from Interface.My implementation is like the code below:
interface Itest
{
T getObject();
}
public class Test1:Itest
{
public T getObject()
{
return (T)(new logger());
}
}
You typically would need to make the interface generic, then return that specific type from the class, ie:
interface ITest<T>
{
T GetObject();
}
public class Test1 : ITest<Logger>
{
public Logger GetObject()
{
return new Logger();
}
}

Generics, Covariance/Contravariance, etc

So I have some Java code that makes extensive use of generics that compiles just fine. I ported it over to C# as follows:
interface IFoo1 { }
interface IFoo2 { }
interface IBar<T, K>
where T : IFoo1
where K : IFoo2 {
List<T> GetFoo1s();
void AddAFoo1(T foo1);
List<K> GetFoo2s();
void AddAFoo2(K foo2);
}
interface IBlip<T>
where T : IBar<IFoo1, IFoo2> {
T DoBlip(string input);
void DoBlip2(T input);
}
interface IConverter<T, K>
where T : IBar<IFoo1, IFoo2>
where K : IBar<IFoo1, IFoo2> {
K Convert(T input);
}
class FooA1 : IFoo1 { }
class FooB1 : IFoo1 { }
class FooA2 : IFoo2 { }
class FooB2 : IFoo2 { }
class BarA : IBar<FooA1, FooA2> {
public List<FooA1> GetFoo1s() { return null; }
public void AddAFoo1(FooA1 foo1) { }
public List<FooA2> GetFoo2s() { return null; }
public void AddAFoo2(FooA2 foo2) { }
}
class BarB : IBar<FooB1, FooB2> {
public List<FooB1> GetFoo1s() { return null; }
public void AddAFoo1(FooB1 foo1) { }
public List<FooB2> GetFoo2s() { return null; }
public void AddAFoo2(FooB2 foo2) { }
}
class BlipA : IBlip<BarA> {
public BarA DoBlip(string input) { return null; }
public void DoBlip2(BarA input) { }
}
class BlipB : IBlip<BarB> {
public BarB DoBlip(string input) { return null; }
public void DoBlip2(BarB input) { }
}
class ConverterImplementation : IConverter<BarA, BarB> {
public BarB Convert(BarA input) {
return null;
}
}
When I compile this, it complains that, for example, with the ConverterImplementation, that BarA cannot be implicitly converted to IBar. I guess there's something that I'm fundamentally missing here. Could someone shed some light on it? Thanks.
Generic type parameters are by default neither contravariant nor covariant, but can be made one or the other via the "in" and "out" keywords.
In the case of IBar<T, K>, both type parameters are used as both inputs and outputs, so you cannot make them either contravariant or covariant. If you refactored it into two interfaces, one in which T is used only for input and K only for output, and one in which T is used only for output and K only for input, then you could make each type parameter covariant or contravariant based on its usage.
IBar is not a read only interface, therefore you may not achieve convariance in C#. You need to refactor and extract a read only interface, e.g. ReadOnlyBar, and do convariance on that interface. (disclaimer - not an expert on C#)
On the other hand, Java's wildcard can turn an interface to read-only and convariant interface, so IBar<? extends Animal> is read-only convariant, and IBar<? extends Tiger> is a subtype of it. That's cool and all, until your code is littered with lots of wildcards.

C# interface function definition concrete implementation

How do I implement the function defined in the interface below? When I implemented in VS2010 like I have below. MyType gets greyed out and it doesn't recongise the type anymore? thanks!
public interface IExample
{
T GetAnything<T>();
}
public class MyType
{
//getter, setter here
}
public class Get : IExample
{
public MyType GetAnything<MyType>()
{ ^^^^^^^ ^^^^^^
MyType mt = new MyType();
^^^^^^^^^^^^^^^^^^^^^^^^^^ /* all greyed out !!*/
}
}
Make a generic interface IExample<T> and then implement it using the concrete type class Get : IExample<MyType> as in the example below.
public interface IExample<T> where T : new()
{
T GetAnything();
}
public class Get : IExample<MyType>
{
public MyType GetAnything()
{
MyType mt = new MyType();
return mt;
}
}
public class MyType
{
// ...
}
Dennis' answer looks like what you want but just in case it isn't, in order to get your code working, you can do this but I'm not sure how much value this really has...
public class Get : IExample
{
public T GetAnything<T>()
{
return default(T);
}
}
public void X()
{
var get = new Get();
var mt = get.GetAnything<MyType>();
}

Categories