The code is simple enough to understand I hope.
I'm trying to use an interface type IColor
in order to pass color objects to the ColorManager
. I then want the ColorManager
to pass this object to the IColor
object as its own type, so the method overloads gets called.
However, it seems since it is being passed as the IColor
type, C# will not implicity cast it into its complete type as either a BlueColor
or GreenColor
.
I hope this makes some sense to somebody on what I want to achieve. Is this possible in C#?
[Solution] http://msdn.microsoft.com/en-us/library/dd264736.aspx Overload Resolution with Arguments of Type dynamic
My code so far:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
namespace Example
{
public interface IColor
{
void CatchColor(IColor c);
}
public class BlueColor : IColor
{
public void CatchColor(IColor c)
{
}
}
public class GreenColor : IColor
{
public void CatchColor(BlueColor c)
{
Console.WriteLine("CAUGHT BLUE!");
}
public void CatchColor(GreenColor c)
{
Console.WriteLine("CAUGHT GREEN!");
}
public void CatchColor(IColor c)
{
Console.WriteLine("CAUGHT SOME COLOR!");
}
}
public class ColorManager
{
public void PassColor(IColor c)
{
// Don't use static type-checking
// Problem solved
dynamic AnyColor = c;
AnyColor.CatchColor(AnyColor);
}
public static void Main()
{
GreenColor G = new GreenColor();
new ColorManager().PassColor(G);
Console.ReadLine();
return;
}
}
}