k1gabi k1gabi - 1 month ago 17
C# Question

Implicit cast on reference type

I have the following code with the explicit cast

a = (Class2)o


using System;

class Class1 { }
class Class2 : Class1{ }

class IsTest
{
static void Test(object o)
{
Class1 a;
Class2 b;

if (o is Class2)
{
Console.WriteLine("o is Class2");
a = (Class2)o; // Works
a = o; // **implicit cast won't work - error CS0266**
}
}
static void Main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
Test(c2);
}
}


When I'm trying to implicit cast a = o it gives me the error CS0266.
From what I know converting a reference type to a direct or indirect ancestor class is a widening conversion, so a program can make the conversion implicitly.

b is derived from a, so why the implicit cast doesn't work?

Answer

It is as per the C# standard:

Thus, conversion operators are not allowed to convert from or to object because implicit and explicit conversions already exist between object and all other types.

https://msdn.microsoft.com/en-us/library/aa664464(v=vs.71).aspx

Additionally to that see all the possible implicit conversions defined in 13.1.4 Implicit reference conversions at the http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf