0
dynamic d = "hello";
Console.WriteLine (d.ToUpper()); // HELLO
Console.WriteLine (d.Foo()); // Compiles OK but gives runtime error

I'm reading a book an stumbled in this section, in the third line it only throws error during runtime but it will compile even though Foo method doesn't exist.

Why not check it in compile time rather than in runtime?

Edit: What is the significance, and when can I use this concept?

Anonymous Duck
  • 2,942
  • 1
  • 12
  • 35
  • You can mark it as duplicate, my only goal in this post is to get input from experienced programmers, you cannot find it all in a book or even in some posts. – Anonymous Duck Jul 20 '16 at 10:33

2 Answers2

4

With dynamic, you are instructing the compiler to ignore it and let the runtime handle it. This is super helpful when dealing with COM and other interfaces that the compiler doesn't know about.

If you want implicit types use var instead. The compiler will infer the type and keep it strongly typed.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • when can I use this technique? or the proper way of using it? – Anonymous Duck Jul 20 '16 at 10:26
  • 3
    @Desperado, the book you are reading should have that explanation of proper use as well. Else, search in SO, there are ample similar question present. – Rahul Jul 20 '16 at 10:28
  • @Rahul yes I read it, but not all concepts and techniques are present. We cannot argue that when we deal with experienced programmers – Anonymous Duck Jul 20 '16 at 10:32
  • thanks bro! This is helpful even if I lost some of my reputations T.T moderators sigh – Anonymous Duck Jul 20 '16 at 10:35
  • Daniel, No complain and your answer is far more correct and I did upvoted but still fill this answer shouldn't have been given keeping in mind that there are already duplicate question present. – Rahul Jul 20 '16 at 10:36
  • 2
    @Rahul the question had morphed since it was originally posted. – Daniel A. White Jul 20 '16 at 10:36
  • @DanielA.White I agree, my question is "Why not check it in compile time rather than in runtime?" and this is unique with the duplicated suggestions – Anonymous Duck Jul 20 '16 at 10:39
4

The dynamic-keyword causes this behaviour which is intended. When making a variable dynamic you can do everything with it making it not compile-time-safe. So by making it dynamic you completely bypass the compiletime-types - that´s why you should take care when using it.

Checking the members at runtime is the whole point of dynamic though - why should it exist otherwise?

I assume you intentionally wanted the var-keyword which gives you compiletime-safety. Have a look at this point for the difference on both. As to the when to use the keyword have a look at this post.

Community
  • 1
  • 1
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111