I am trying to understand what Enumerable.Cast
does to perform the cast, and why I can't get it to work even when an implicit (or explicit) conversion operator has been defined for the target types.
The following code puts together a few tests I've prepared to understand what was going wrong. What I'm really after is understanding why test5
throws and InvalidCastException
; however at this stage I think that the problem is connected in the failure of test3
and test4
.
void Main()
{
List<Currency> values = new List<Currency>() { new Euro(), new Dollar() };
Dollar d = new Dollar();
Euro e = new Euro();
var test1a = (Dollar)e; // valid
var test1b = (Euro)d; // valid
Console.WriteLine(values[0].GetType()); // Euro
var test2 = values[0] as Dollar; // valid
var test3 = (Dollar)values[0]; // Why does this fail? - InvalidCastException: Unable to cast object of type 'Euro' to type 'Dollar'
var test4 = values.Cast<Euro>(); // no error
Console.WriteLine(test4.ToString()); // what's this CastIterator?
var test5 = test4.ToList(); // Why does this fail? - InvalidCastException: Unable to cast object of type 'Dollar' to type 'Euro'
}
class Currency { public double Amount {get; set;} = 0; }
class Euro : Currency
{
public Euro(double amount = 0) { this.Amount = amount; }
public static implicit operator Euro(Dollar d)
{
Euro e = new Euro(); e.Amount = d.Amount*1.2; return e;
}
}
class Dollar : Currency
{
public Dollar(double amount = 0) { this.Amount = amount; }
public static implicit operator Dollar(Euro e)
{
Dollar d = new Dollar(); d.Amount = e.Amount/1.2; return d;
}
}
As you can see, I've specified implicit conversion operators for the classes, however that's not enough for test3 and 4 to work. Why is that?