The following code has a static method, Foo()
, calling an instance method, Bar()
:
public sealed class Example
{
int count;
pub
The "dynamic" expression will be bound during runtime, so if you define a static method with the correct signature or a instance method the compiler will not check it.
The "right" method will be determined during runtime. The compiler can not know if there is a valid method there during runtime.
The "dynamic" keyword is defined for dynamic and script languages, where the Method can be defined at any time, even during runtime. Crazy stuff
Here a sample which handles ints but no strings, because of the method is on the instance.
class Program {
static void Main(string[] args) {
Example.Foo(1234);
Example.Foo("1234");
}
}
public class Example {
int count;
public static void Foo(dynamic x) {
Bar(x);
}
public static void Bar(int a) {
Console.WriteLine(a);
}
void Bar(dynamic x) {
count++;
}
}
You can add a method to handle all "wrong" calls, which could not be handled
public class Example {
int count;
public static void Foo(dynamic x) {
Bar(x);
}
public static void Bar(T a) {
Console.WriteLine("Error handling:" + a);
}
public static void Bar(int a) {
Console.WriteLine(a);
}
void Bar(dynamic x) {
count++;
}
}