Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# type casting to a generic interface

Tags:

c#

generics

I am writing a library that renders a bunch of child objects to screen. The child object is abstract, and it is intended for users of this library to derive their own child from this abstract class.

public abstract class Child : IRenderable {}

public interface IParent<T> where T : Child
{
   IEnumerable<T> Children { get; }
}

The complication is that I do not have a list of IParent to work with, instead, I have a bunch of IRenderables. The user of the library is expected to write something like this:

public class Car : IRenderable { }
public class Cow : IRenderable, IParent<Calf> { }
public class Calf : Child { }

// note this is just an example to get the idea
public static class App
{
   public static void main()
   {
      MyLibraryNameSpace.App app = new MyLibraryNameSpace.App();
      app.AddRenderable(new Car()); // app holds a list of IRenderables
      app.AddRenderable(new Cow());
      app.Draw(); // app draws the IRenderables
   }
}

In Draw(), the library should cast and check whether the IRenderable is also an IParent. However, since I do not know about the Calf, I don't know what to cast Cow into.

// In Draw()
foreach(var renderable in Renderables)
{
   if((parent = renderable as IParent<???>) != null) // what to do?
   {
      foreach(var child in parent.Children)
      {
          // do something to child here.
      }
   }
}

How can I overcome this problem? Is this anything to do with covariance generics or what-so-ever (I am not familiar with the covariance concept)?

like image 328
Jake Avatar asked Apr 13 '12 05:04

Jake


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


3 Answers

Since IParent<T> only returns items of type T, you could make it covariant using the out modifier:

public interface IParent<out T> where T : Child
{
   IEnumerable<T> Children { get; }
}

This would make IParent<anything> convertible to IParent<Child>:

IParent<Child> parent = renderable as IParent<Child>; // works for Cow

Note that covariance only works as long as you are only returning objects of type T (simply speaking). For example, as soon as you add an AddChild(T) method to your IParent interface, covariance must break (= the compiler will complain), since, otherwise, the following type-unsafe code could be written:

IParent<Child> parent = renderable as IParent<Child>;
parent.AddChild(new Kitten()); // can't work if parent is really a Cow.
like image 72
Heinzi Avatar answered Oct 17 '22 15:10

Heinzi


You could implement intermediate non-generic interface IParent:

public interface IParent
{
    IEnumerable<Child> Children { get; }
}

public interface IParent<T> : IParent
  where T: Child
{
    IEnumerable<T> Children { get; }
}

And then cast to IParent in your function.

like image 25
Dmitry Reznik Avatar answered Oct 17 '22 16:10

Dmitry Reznik


Something along the following lines?

static void draw(List<IRenderable> renderables)
{
    foreach (IRenderable render in renderables)
    {
        if (render is IParent<Child>)
        {
            foreach (Child c in ((IParent<Child>)render).Children)
            {
                //do something with C?
            }
        } 
    }
}
like image 1
Brad Mccormack Avatar answered Oct 17 '22 17:10

Brad Mccormack