I have a large MVC4 app in VS2012 with controller functions that return simple dynamic objects (as JSON) back to jQuery $.post functions.
It appears the compiler is combining objects with the same property definitions (but different letter cases) into the same object. This is causing issues when trying to read back the properties in javascript.
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer()
'should return {"TEST":true} and does
MessageBox.Show(js.Serialize(New With {.TEST = True}))
' should return {"test":true} but returns {"TEST":true} if the above code exists.
MessageBox.Show(js.Serialize(New With {.test = True}))
The project is large with multiple developers, so it's not always practical to scan the code for instances of this issue.
Is there a way to prevent this optimization?
VB.Net is not case sensitive, and thus will consider differently cased dynamic types to be identical. It is just how the language works, and not something that can be changed. Similarly, Classes/parameters, etc that only differ by case are considered the same/not allowed. This is not a "Compiler optimization" but rather how the language works.
Dynamic types, by the nature of how the compiler creates them, must collapse identical signatures into one type (lest you never be able to create the same type again). That combined with VB's nature means you are stuck.
So you really have a few options:
Enforce consistent coding case standards across your org. This can be imposed via check-in policies, code reviews, or whatever process works for you.
With the new static analysis and compiler source now available, you likely can build a static code analysis rule to detect this scenario. But it won't be easy.
Use named classes for return types to avoid the issue altogether. I know you are scared of class bloat, but if you are using the same dynamic types in multiple controllers, you probably should have static classes anyway. And really, what's the cost of a file? Nothing. This is the best option, and the most maintainable of the three.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With