interface - Why does C# tease with structural typing when it absolutely knows it doesn't have it? -
i surprised see today possible, worry must discussed before.
public interface icanadd { int add(int x, int y); } // note myadder not implement icanadd, // define add method 1 in icanadd: public class myadder { public int add(int x, int y) { return x + y; } } public class program { void main() { var myadder = new myadder(); var icanadd = (icanadd)myadder; //compiles, sake? int sum = icanadd.add(2, 2); //na, not game it, cast had failed } }
the compiler (rightly?) tell me explicit cast exists in above situation. thrilled sense structural typing in there, no run time fails. when c# being ever helpful here? scenarios such casting work? whatever is, i'm sure compiler beforehand knows myadder
not icanadd
, technically.
c# allows explicit conversion class interface (even if class doesn't implement interface), because compiler knows, reference type might (the uncertainty why it's explicit rather implicit conversion) instance of derived type does implement interface. extending example, suppose have:
public class derivedadder : myadder, icanadd { int icanadd.add(int x, int y) { return base.add(x, y); } } ... myadder myadder = new derivedadder(); var icanadd = (icanadd)myadder; // valid in case int sum = icanadd.add(2, 2); // sum = 4
if check section 6.2.4 of c# specification, you'll see if mark myadder
class sealed
, compiler complain, because know sure no conversion possible, since no derived type exist. long can't eliminate every last shred of doubt, it'll allow explicit conversion.
Comments
Post a Comment