Cannot cast the type into its generic parameter using operator (op_Implicit or op_Explicit) even if nothing runs wrong (using reflection) #94633
-
It seems an operator declaration with a generic parameter of class would not work. An interface: namespace TestProject1;
public interface IWrapper<TWrapper, TWrapped> where TWrapper : IWrapper<TWrapper, TWrapped>
{
public TWrapped Wrapped { get; }
public static virtual implicit operator TWrapped(TWrapper @this) => @this.Wrapped;
} It represents a wrapper and it can be cast into And two same wrappers: namespace TestProject1;
public class Wrapper1<TWrapped> : IWrapper<Wrapper1<TWrapped>, TWrapped>
{
public Wrapper1(TWrapped wrapped)
{
Wrapped = wrapped;
}
public TWrapped Wrapped { get; }
} and namespace TestProject1;
public class Wrapper2<TWrapped> : IWrapper<Wrapper2<TWrapped>, TWrapped>
{
public Wrapper2(TWrapped wrapped)
{
Wrapped = wrapped;
}
public TWrapped Wrapped { get; }
} and namespace TestProject1;
public class GenericCast<T>
{
public T val;
public GenericCast(T val)
{
this.val = val;
}
public static implicit operator T(GenericCast<T> @this) => @this.val;
} However, now, the cast from var wrapper1 = new Wrapper1<Wrapper2<int>>(new Wrapper2<int>(42));
// Console.WriteLine((wrapper1 as Wrapper2<int>).Wrapped); // does not work, even if `TWrapped` is `Wrapper2<int>`
var g = new GenericCast<string>("Value");
// Console.WriteLine(g as string); // does not work
// Console.WriteLine(GenericCast<string>.op_Implicit(g)); // CS0571
Console.WriteLine(typeof(GenericCast<string>).GetMethod("op_Implicit").Invoke(null, new object?[]{g})); // reflection works well Even though I think this is strange, is this a bug? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Beta Was this translation helpful? Give feedback.
From:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#as-operator