Dynamic objects in c#

Whare are dynamic objects in c#?

C# is considered a strongly typed programming language, however there are some cases when an object has to be defined dynamically, that is, we neither know the type and if we assign it with a value of some type, we can later assign it with another unrelated type

To make it more complicated we would expect to create a dynamic type which we construct during runtime, that is, e.g. defining its properties or fields, maybe with some similarity of what can be achieved in javascript with prototype

Here are some examples of what can be done in c# dynamically

To create an anonymous class, we can use the following syntax

var a = new { PropName = Value }

That creates an object with a property of "PropName".

What if we want to create an object with dynamic property names, something like:

var a = new { [PropNameFromInput] = Value }

For this we need to use the ExpandoObject as following:

var kv = new ExpandoObject() as IDictionary<string, object>;
kv.Add("SomePropName", "SomePropValue"));

Then, we can pass this variable to e.g. Dapper like this:


await connection.ExecuteAsync("SELECT * FROM SomeTable WHERE SomePropName=@SomePropName", kv);

Post a Comment

Previous Post Next Post