Dynamic object returned

I have a simple data-level procedure that updates the password, the user passes the following:

  • Current password, new password, confirmation of the new password.

In my data layer (proc) several things are checked, such as:

  • Is the current password correct?
  • Is the new password correct and confirm the password?
  • Has a new password been assigned in the past?

And so on...

Now I know that I can just create a class and return a couple of logical elements:

public class UpdatePasswordResponse{ public bool CurrentPasswordCorrect {get;set;} ....(and so on) } 

But is there a way to dynamically return this information to the biz level in the properties, and not create a new class each time (for each data-level procedure)? I think I remember that it was possible. I'm sure I read it somewhere, but I don’t remember the syntax, can someone help me?

+4
source share
2 answers

You can do this in .NET 4 using the dynamic keyword.

The class you want to return will be 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; 
+16
source

If you just want to dynamically create the class you are writing:

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

Source: https://habr.com/ru/post/1399255/


All Articles