Created
November 3, 2017 13:10
-
-
Save M-Yankov/7d30a3aebb3ab24c02e8dde92fc08603 to your computer and use it in GitHub Desktop.
How to get all properties from a dynamic model.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dynamic person = new object { Name = "John", Age = 32, Title = "HR" }; | |
// In case the person comes from somewhere else | |
if (person != null) | |
{ | |
var properties = person.GetType().GetPtoperties(); // Will return an Array of System.Reflection.PropertyInfo[]; | |
// or | |
Type theType = (Type)person.GetType(); | |
// and then we would have an intellisense in Visial Studio. | |
System.Reflection.PropertyInfo nameProperty = theType.GetProperty("Name"); | |
nameProperty.GetValue(person); | |
// currently this example is very obvious. And we gonna use something like. | |
person.Name; | |
} | |
// The real usage comes when we are using a specific framework, package, library etc. | |
// And we have a method that returns dynamic: | |
var configurationSettings = GeSettings(); | |
configurationSettings.Fields; // Items is dynamic. Now what? | |
// Similar to the above example: | |
if (configurationSettings.Fields != null) | |
{ | |
Type fieldsType = (Type)configurationSettings.Fields.GetType(); | |
// use reflection for more iteractions | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment