Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 905
Morgan Cheng Avatar asked May 13 '10 08:05

Morgan Cheng


People also ask

Can a static method be invoked?

Unlike instance methods, a static method is referenced by the class name and can be invoked without creating an object of class.

How can I call static method?

A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.

Can I call a static function from another file in C?

Functions in C are global by default. To make them local to the file they are created, we use the keyword static before the function. Static functions can't be called from any other file except the file in which it is created.

How do you call a static method in a class?

Calling Static FunctionIt is invoked by using the class name. For example: Math. sqrt(a); //calling the square root function of the Math class.


1 Answers

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

like image 95
Julien Lebosquain Avatar answered Oct 10 '22 12:10

Julien Lebosquain