Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the dynamic keyword in C#4 support extension methods?

I'm listening to a talk about C#4's dynamic keyword and I'm wondering... Will this feature be orthogonal to other .NET features, for example will it support extension methods?

public static class StrExtension {     public static string twice(this string str) { return str + str; } } ... dynamic x = "Yo"; x.twice(); // will this work? 

Note: This question was asked before C#4 was shipped which is why it's phrased in the future tense.

like image 462
Motti Avatar asked Nov 03 '08 15:11

Motti


People also ask

What is VAR and dynamic keyword in C#?

dynamic variables can be used to create properties and return values from a function. var variables cannot be used for property or return values from a function. They can only be used as local variable in a function.

Is C# static or dynamic?

C# and Java are often considered examples of statically typed languages, while Python, Ruby and JavaScript are examples of dynamically typed languages.

Should we use dynamic in C#?

The dynamic type has been added to C# since version 4 as because of the need to improve interoperability with COM (Component Object Model) and other dynamic languages. While that can be achieved with reflection, dynamic provides a natural and more intuitive way to implement the same code.


2 Answers

From the "New Features in C# 4" word doc:

Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not currently kept as part of the payload.

like image 174
Jon Skeet Avatar answered Sep 23 '22 12:09

Jon Skeet


This works which I find interesting at least...

public static class StrExtension {    public static string twice(this string str) { return str + str; } }  ... dynamic x = "Yo"; StrExtension.twice(x); 

Still, if the compiler can find the correct extension method at compile time then I don't see why it can't package up a set of extension methods to be looked up at runtime? It would be like a v-table for non-member methods.

EDIT:

This is cool... http://www2.research.att.com/~bs/multimethods.pdf

like image 34
Ian Warburton Avatar answered Sep 20 '22 12:09

Ian Warburton