Quantcast
Channel: Visual C# forum
Viewing all articles
Browse latest Browse all 31927

C#, "dynamic" and compile time checking

$
0
0

I understand the behavior of "dynamic" and think its a great concept, it has several valuable uses.

However I don't see why the compiler doesn't try to do SOME type checking on uses of dynamic variables.

For example:

        public Form1()
        {
            InitializeComponent();

            var x = 2;

            dynamic y = "Hello";

            int c = x + y;

        }

It is indisputable that this will lead to an exception at runtime and there's no way it could ever be avoided, the variables are all local (stack) to the function so cannot be asynchronously modified by other threads, "y" is not modified after the string is assigned to it etc.

The compiler can in fact safely convert this to:

        public Form1()
        {
            InitializeComponent();

            var x = 2;

            string y = "Hello";

            int c = x + y;

        }

So it would surely be better to report this at compile time in some way (it could be code that might not get tested for some reason and so possibly lead to a runtime failure under difficult circumstances).

It strikes me that the compiler engineers have been a little lax here - any problem that a compiler can reliably detect should be reported during compilation in my opinion.

Cap'n

a





Viewing all articles
Browse latest Browse all 31927

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>