TheWebGuy
TheWebGuy

Reputation: 12605

Return dynamic object

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:

  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?

Upvotes: 19

Views: 60755

Answers (2)

Randolpho
Randolpho

Reputation: 56419

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;

Upvotes: 36

Mattias Åslund
Mattias Åslund

Reputation: 3907

If you just want to dynamically create a class you write:

public object MyMethod()
{
     var result = new { Username = "my name", Password = "the password" };
     return result;
}

Upvotes: 21

Related Questions