Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can method parameters be dynamic in C#

In c# 4.0, are dynamic method parameters possible, like in the following code?

public string MakeItQuack(dynamic duck) {   string quack = duck.Quack();   return quack; } 

I've many cool examples of the dynamic keyword in C# 4.0, but not like above. This question is of course inspired by how python works.

like image 631
Pimin Konstantin Kefaloukos Avatar asked Nov 12 '09 17:11

Pimin Konstantin Kefaloukos


People also ask

What is the dynamic parameter?

Dynamic parameters can be strings, measure values, or dates, offering flexibility and interactivity when building a dashboard for your audience. Because they can be easily used in most analytical entities, dynamic parameters give you programmatic control to customize your analysis.

What are method parameters in C#?

Parameters act as variables inside the method. They are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. The following example has a method that takes a string called fname as parameter.


1 Answers

Yes, you can absolutely do that. For the purposes of static overload resolution, it's treated as an object parameter (and called statically). What you do within the method will then be dynamic. For example:

using System;  class Program {     static void Foo(dynamic duck)     {         duck.Quack(); // Called dynamically     }      static void Foo(Guid ignored)     {     }      static void Main()     {         // Calls Foo(dynamic) statically         Foo("hello");     } } 

The "dynamic is like object" nature means you can't have one overload with just an object parameter and one with just a dynamic parameter.

like image 55
Jon Skeet Avatar answered Nov 11 '22 15:11

Jon Skeet