Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return dynamic object

Tags:

c#

asp.net

I have a simple data layer routine that performs a password update, the user passes in the following:

  • Current Password, New Password, Confirm New Password.

In my data layer (proc) checks a couple things such as:

  1. Is the current password correct?
  2. Is the new password and confirm password correct?
  3. Has the new password been assigned in the past?

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?

like image 974
TheWebGuy Avatar asked Mar 01 '12 20:03

TheWebGuy


People also ask

Can return type be dynamic?

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.

What is dynamic return type in C#?

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.

What is a dynamic object?

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.

What are dynamic objects C++?

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.


1 Answers

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;
like image 169
Randolpho Avatar answered Sep 20 '22 21:09

Randolpho