1

My class ClassName has an operator defined:

public static explicit operator ClassName(Guid value)
{
    return new ClassName(value);
}

This allows to "cast" this way:

var guids = new[] { Guid.NewGuid, Guid.NewGuid() };

var classes = guids.Select(g => (ClassName)g).ToArray();

If I had a method like

public static ClassName Convert(Guid value)
{
    return new ClassName(value);
}

I could use the method group:

var guids = new[] { Guid.NewGuid, Guid.NewGuid() };

var classes = guids.Select(ClassName.Convert).ToArray();

Is there a way to just pass the method group for the explicit operator as well?

My naive experiments at correct syntax have failed:

guids.Select(ClassName) // no (obviously)

guids.Select(ClassName.ClassName) // no (obviously)

guids.Select((ClassName)) // no (obviously)

guids.Select(ClassName.op_explicit)  // no (obviously)
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • I don't think so as there's no way in c# to invoke the method itself (similar to operations). Can you just `guids.Cast()` instead? – pinkfloydx33 Jun 26 '18 at 08:53
  • @pinkfloydx33 No, implicit and explicit operators can't be used by `.Cast<>()` – xanatos Jun 26 '18 at 09:07
  • @xanatos really? The reference source performs a direct cast: `yield return (TResult)obj;` why wouldn't that work? https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,152b93d25e224365,references – pinkfloydx33 Jun 26 '18 at 09:11
  • 2
    @pinkfloydx33 But implicit and explicit cast operators can't be used. Only up-down casting is permitted. This because the C# compiler can't know the type of `T`, so it can't go looking for implicit and explicit operators. You must always remember that cast operators are syntactic sugar for "special" methods (named `op_implicit`/`op_explicit`): but with generics you can't access methods of T unless you give a restriction like `where T : SomeClass`, then you can use methods of `SomeClass` for `T`, because the compiler knows that `T` is a `SomeClass` – xanatos Jun 26 '18 at 09:15
  • @xanatos Ignore my last (deleted) comment. Its 5am--missed my blatant error – pinkfloydx33 Jun 26 '18 at 09:33
  • Just a note, I'm not attached to that `Select`, if the `Cast<>` option would have worked, that would have been nice too. – nvoigt Jun 26 '18 at 09:56

0 Answers0