Run-time exception about type dynamic and type object in C#:


public void Print(string arg)
{
    return;
}

 

A) Compiler error:


// A.1) Compiler error:
//  At compile time the type of obj is System.Object.
object obj = 10;
obj = obj + 10;  //obj = (int)obj + 10;

 


// A.2) Compiler error.
object obj = 10;  //object obj = "10";
Print(obj);       //Print((string)obj);

 

B) Run time exception:


// B.1) Run time exception: obj is an integer, not a string.
object obj = 10;
obj = (string)obj + 10;  //obj = (int)obj + 10;

 


// B.2) Run time exception: Cast to a wrong numeric type.
object obj = 10;
obj = (double)obj + 10;  //obj = (int)obj + 10;

 


// B.3) Run time exception.
object obj = 10;     //object obj = "10";
Print((string)obj);  //Print((string)obj);

 


// B.4) Run time exception:
//  The only way you can pass a dynamic object
//  to your method is if it contains a necessary value.
dynamic dyn = 10;  //dynamic dyn = "10";
Print(dyn);

 

C) No error:


// C.1) No error:
object obj = 10;
obj = (int)obj + 10;

 


// C.2) No error: The compiler does not try to identify
//  the type of the dynamic object at compile time.
dynamic dyn = 10;
dyn = dyn + 10;

 


// C.3) No error:
//  Success for all other types that support a “+” operation.
dynamic dyn = 10.0;
dyn = dyn + 10;
dyn = "10";
dyn = dyn + 10;

 


// C.4) No error: Still need a cast.
object obj = "10";
Print((string)obj);

 


// C.5) No error.
dynamic dyn = "10";
Print(dyn);

 

 

Reference:

What is the difference between “dynamic” and “object” keywords? https://blogs.msdn.microsoft.com/csharpfaq/2010/01/25/what-is-the-difference-between-dynamic-and-object-keywords

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Google photo

您的留言將使用 Google 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s