Can method parameters be dynamic in C#

49,237

Solution 1

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.

Solution 2

See documentation http://msdn.microsoft.com/en-us/library/dd264741(VS.100).aspx

Solution 3

Yes, you can do that. As stated in C# 4.0 specification, the grammar is extended to support dynamic wherever a type is expected:

type:
       ...
      dynamic

This includes parameter definitions, of course.

Share:
49,237
Pimin Konstantin Kefaloukos
Author by

Pimin Konstantin Kefaloukos

Current problems: Data analytics, data science, machine learning, prediction. Current technologies: Apache Spark, Python, Amazon Web Services.

Updated on November 13, 2020

Comments

  • Pimin Konstantin Kefaloukos
    Pimin Konstantin Kefaloukos over 3 years

    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.

  • 3Dave
    3Dave over 14 years
    Note that that article implies very inefficient late binding. Strong typing is your friend!
  • Jon Skeet
    Jon Skeet over 14 years
    @David: The dynamic behaviour in the DLR is pretty neatly done to be as efficient as is sanely possible. Yes, it's late-bound, but it's not as inefficient as you might expect.
  • BitMask777
    BitMask777 over 9 years
    If I'm correctly understanding this updated article by ChrisB (blogs.msdn.com/b/cburrows/archive/2010/04/01/…) then it seems this behavior may have changed. Sounds like calls are always dispatched dynamically, with the overload chosen according to the type(s) of the parameters as determined at runtime.
  • Jon Skeet
    Jon Skeet over 9 years
    @BitMask777: Only if one of the arguments (or target) is dynamic. So in the code in my answer, the Foo("hello") doesn't have any dynamic arguments, so Foo(dyanmic) is statically bound.