Dynamic Typing in c#

Consider the below example for better understanding a corner case of Dyamic typing.

List<Int> list1= new List<Int>();

Console.WriteLine(list1.IsFixedSize);

(The above code will give compile time error)

IList list2 = list1;

Console.WriteLine(list2.IsFixedSize);

(Successfully Prints False)

dynamic list3 =list1;

Console.WriteLine(list3.IsFixedSize);

(Execution time error)

List<T> implements IList interface. The interface has a property called IsFixedSize but List<T> class implements that explicitly. Any attempt to access it via expression with a static type fail at compile time. You can access it with a static type of IList and it will always return false .But the million dollar question is what about dynamic ? The binder will always use the Concrete type of the dynamic value , So it fails to find the property at runtime and thrown RunTimeBinder Exception . The workaround is to convert the dynamic value back to the interface (casting or using separate variable).


要查看或添加评论,请登录

Sayed Azharuddin的更多文章

社区洞察

其他会员也浏览了