You have to be a bit tricky or extra careful when working with the dynamic type, because this is a runtime type which never gets checked by the compiler at compile time.
Hence, writing the code with the dynamic type needs some care. Dynamic is not a safe type, because the compiler never checks type when compiling the code.
Following are the cases, that you can consider, when a method is called on the dynamic type.
- Explicitly implemented Interface
If a class implements an interface explicitly and you want to call the explicitly implemented method using
dynamic type, it will throw an exception i.e. RuntimeBinderException.
- interface IOrder {
- string ModifyOrderNumber();
- }
- public class Order: IOrder {
- public string OrderNumber {
- get;
- set;
- }
- public string IOrder.ModifyOrderNumber()
- {
- return "FlipKart" + OrderNumber;
- }
- }
- If you
- try to call your method like below: public class Program {
- public static void main(string[] args) {
- IOrder order = new Order() {
- OrderNumber = "TestOrder"
- };
- dynamic dynamicOrder = order;
- dynamicOrder.ModifyOrderNumber();
- }
- Extension methods
We can not call the Extension method on the dynamic type. It will throw a RuntimeBinderException. The Extension methods are a compile time concept and not for run time. The Extension methods will give you a RuntimeBinderException error.
- static class ExtensionMethods {
- public static string ToString(this string s) {
- return string.format("Hi, {0}", s);
- }
- }
- public class Program {
- public static void main(string[] args) {
- dynamic s = "greeting";
- Console.WriteLine(s.ToString());
- }
- }
- What you can do is: static class ExtensionMethods {
- public static string ToString(this string s) {
- return string.format("Hi, {0}", s);
- }
- }
- public class Program {
- public static void main(string[] args) {
- dynamic s = "greeting";
- string formattedString = ExtensionMethods.ToString(s);
- Console.WriteLine(formattedString);
- }
- }
- Working with void methods
It will again give you a RuntimeBinderException if you are trying to call the methods whose return type is void on the dynamic type.
- public class Worker {
- public void DoSomething() {
- Console.WriteLine("I do nothing");
- }
- }
- public class Program {
- public static void main(string[] args) {
- Worker worker = new Worker();
- dynamic dynamicWorker = worker;
- dynamicWorker.DoSomething();
- }
- }