Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface methods to return dynamic

Would there be any downside if, as of .NET 4.0's release, all interface methods were changed from returning object to returning dynamic?

Existing code would not have to be altered due to it since the underlying type would still be the same and it would make for slightly less verbose code.

public class MyClass : IClonable
{
    //...
    public object Clone()
    {
        //...
        return new MyClass(...);
    }
}

MyClass foo = new MyClass(...);
MyClass bar = foo.Clone() as MyClass;

The only reduction to the verbosity of the code above is changing the declaration of foo and bar to var.

Now, if IClonable.Clone() returned a dynamic instead, the underlying class (at runtime) would still be MyClass, but the code would become slightly less verbose:

MyClass foo = new MyClass(...);
MyClass bar = foo.Clone();

Would there be any downside to such a change?

like image 342
Wasabi Avatar asked Feb 13 '23 19:02

Wasabi


2 Answers

One downside to this change would be compiler's inability to catch errors caused by typos. For example, if you wrote

if (foo.Clone().Equalls(foo)) {
//                  ^^
//                  ||
// Here is a typo ==++
}

with your Clone() returning an object, the compiler would catch it. With a change to dynamic the compiler would take it fine, so your program would throw a runtime exception for a missing method.

like image 131
Sergey Kalinichenko Avatar answered Feb 15 '23 10:02

Sergey Kalinichenko


Yes, one major downside would be that dynamics do not provide compile-time safety... or useful intellisense for that matter. So not only would it take longer and be more error prone accessing a property on an object, but if you did make a mistake, you wouldn't catch it until runtime.

It won't always be the case, but often the example of "verbosity" you give could be better avoided by generics. ICloneable is an example of an interface where for some reason (possibly historic) there is no generic version, but when there is a generic version, it means that you can return the exact type you need rather than an object that must be cast.

like image 41
Ben Aaronson Avatar answered Feb 15 '23 10:02

Ben Aaronson