Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an extension method of a dynamic type?

Tags:

I'm reading the book 'C# in Depth, 2nd Edition' of Jon Skeet. He said that we can call extension methods with dynamic arguments using two workarounds, just as

dynamic size = 5; var numbers = Enumerable.Range(10, 10); var error = numbers.Take(size); var workaround1 = numbers.Take((int) size); var workaround2 = Enumerable.Take(numbers, size); 

Then he said "Both approaches will work if you want to call the extension method with the dynamic value as the implicit this value". I don't know how to achieve it.

Thanks a lot.

like image 268
Kirin Yao Avatar asked Mar 11 '11 08:03

Kirin Yao


People also ask

How do you call an extension method?

To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.

Do extension methods have to be static?

An extension method must be a static method. An extension method must be inside a static class -- the class can have any name. The parameter in an extension method should always have the "this" keyword preceding the type on which the method needs to be called.

How do you declare an extension method in C#?

string s = "Hello Extension Methods"; int i = MyExtensions. WordCount(s); The preceding C# code: Declares and assigns a new string named s with a value of "Hello Extension Methods" .

What is extension method in MVC?

What is extension method? Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.


1 Answers

Like this:

dynamic numbers = Enumerable.Range(10, 10); var firstFive = Enumerable.Take(numbers, 5); 

In other words, just call it as a static method instead of as an extension method.

Or if you know an appropriate type argument you could just cast it, which I'd typically do with an extra variable:

dynamic numbers = Enumerable.Range(10, 10); var sequence = (IEnumerable<int>) numbers; var firstFive = sequence.Take(5); 

... but if you're dealing with dynamic types, you may well not know the sequence element type, in which case the first version lets the "execution time compiler" figure it out, basically.

like image 66
Jon Skeet Avatar answered Sep 29 '22 13:09

Jon Skeet