I realize that it goes against the strongly typed nature of C#, but I find that when working with dynamic objects in the language, some of the more useful features typically found in JavaScript or PowerShell are simply not practical.
For example, the following C# code will fail at runtime and it's obvious why.
dynamic x = 1.0; int y = x;
But that makes the dynamic features of C# pretty limited when dealing with loosely typed data such as that produced by JSON payloads or CSV where subtle variations in the representation can result in very different behavior at runtime.
What I'm looking for is something that will behave much like the VBA / VBScript era Variant
type. I imagine it's possible to derive such a type from DynamicObject
that would wrap primitive values like Int32
, String
, etc and perform the appropriate casts at runtime. I've done something similar with "null" values in dynamic contexts.
But is there anything like this already established? I've looked around GitHub or Codeplex to no avail but it's kind of a hard thing to search for. Before I get started on what I imagine is going to be quite a complicated class, I want to make sure I'm not wasting my time.
About the practicality of all of this
I should note that I resisted the concept of dynamic dispatch in C# for a long time because it was not intended to be a dynamic language. Quite honestly, I wish it wasn't added to the language at all, or at least restricted to COM interop scenarios.
But having said that, I am always curious about ways to "hack" language features in such a way to make them do things that they were never intended to do. Sometimes something useful comes out of it. For example, there have been plenty of examples of people using the IDisposable
interface and using
statement to do things that have nothing to do with releasing resources.
I doubt I would use this in production applications or anything that needed to be handed off to another developer.