How to invoke static method in C#4.0 with dynamic type?
Asked Answered
S

3

14

In C#4.0, we have dynamic type, but how to invoke static method of dynamic type object?

Below code will generate exception at run time. The dynamic object is from C# class, but it could be object from other languages through DLR. The point is not how to invoke static method, but how to invoke static method of dynamic object which could not be created in C# code.

class Foo
{
    public static int Sum(int x, int y)
    {
        return x + y;
    }
}

class Program
{

    static void Main(string[] args)
    {
        dynamic d = new Foo();
        Console.WriteLine(d.Sum(1, 3));

    }
}

IMHO, dynamic is invented to bridge C# and other programming language. There is some other language (e.g. Java) allows to invoke static method through object instead of type.

BTW, The introduction of C#4.0 is not so impressive compared to C#3.0.

Syst answered 13/5, 2010 at 8:33 Comment(0)
A
13

This is not supported directly by C# 4 but there's an interesting workaround in this blog post: http://blogs.msdn.com/davidebb/archive/2009/10/23/using-c-dynamic-to-call-static-members.aspx

Annamaeannamaria answered 13/5, 2010 at 8:40 Comment(0)
A
10

While C# doesn't support it, the DLR does. You can programmatically access the dlr calls with Dynamitey

var staticContext = InvokeContext.CreateStatic ;

Console.WriteLine(Dynamic.InvokeMember(staticContext(typeof(Foo)), "Sum", 1,3));
Acima answered 24/6, 2011 at 16:45 Comment(0)
M
7

One possible workaround would be to use reflection.

dynamic d = new Foo();

var sum = (int)d.GetType()
                .GetMethod("Sum")
                .Invoke(d, new object[] { 1, 3 });
Console.WriteLine(sum);
Matthaus answered 13/5, 2010 at 8:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.