Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable<T>.Cast won't work even if an explicit cast operator is defined?

Tags:

c#

I have an explicit conversion defined from type Bar to type Foo.

public class Bar
{
  public static explicit operator Foo(Bar bar)
  {
    return new Foo(bar.Gar);
  }
}

public class Foo
{
  public string Gar { get; set; }

  public Foo() { }

  public Foo(string gar) { Gar = gar; }
}

However, when I do:

using System.Linq;

...

var manyFoos = manyBars.Cast<Foo>();

It throws an exception saying it can't cast.

How do I tell Cast to use my cast operator to try the conversion?

like image 280
Water Cooler v2 Avatar asked Sep 23 '13 06:09

Water Cooler v2


1 Answers

Cast operators are static methods that the compiler calls when you use casts in code. They cannot be used dynamically. Enumerable.Cast does a runtime cast of two unconstrained generic types, so it cannot know during compile time which cast operators to use. To do what you want, you can use Select:

manyFoos.Select(foo => (Bar)foo);
like image 112
Eli Arbel Avatar answered Oct 03 '22 22:10

Eli Arbel