I have a simple data layer routine that performs a password update, the user passes in the following:
In my data layer (proc) checks a couple things such as:
And so on...
Now I know I can simply create a class and returned a couple booleans:
public class UpdatePasswordResponse{
public bool CurrentPasswordCorrect {get;set;}
....(and so on)
}
But is there a way I can dynamically return that information to the biz layer in properties instead of creating a new class everytime (for every data layer routine)? I seem to remember thinking this was possible. I am pretty sure I read it somewhere but don't remember the syntax, can someone help me?
Yes there are ways by which you can deliver different objects on run time and dynamic is one of those solution. Today, we will understand how to use dynamic keyword to return a whole different object on runtime. You can even change the return type based on your input.
C# 4.0 (. NET 4.5) introduced a new type called dynamic that avoids compile-time type checking. A dynamic type escapes type checking at compile-time; instead, it resolves type at run time. A dynamic type variables are defined using the dynamic keyword.
Dynamic objects expose members such as properties and methods at run time, instead of at compile time. This enables you to create objects to work with structures that do not match a static type or format.
In C++, the objects can be created at run-time. C++ supports two operators new and delete to perform memory allocation and de-allocation. These types of objects are called dynamic objects. The new operator is used to create objects dynamically and the delete operator is used to delete objects dynamically.
You can do this in .NET 4 with the use of the dynamic
keyword.
The class you will want to return would be an ExpandoObject.
Basically, follow this pattern:
public object GetDynamicObject()
{
dynamic obj = new ExpandoObject();
obj.DynamicProperty1 = "hello world";
obj.DynamicProperty2 = 123;
return obj;
}
// elsewhere in your code:
dynamic myObj = GetDynamicObject();
string hello = myObj.DynamicProperty1;
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