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.
Unlike instance methods, a static method is referenced by the class name and can be invoked without creating an object of class.
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.
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.
Calling Static FunctionIt is invoked by using the class name. For example: Math. sqrt(a); //calling the square root function of the Math class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With