C# Iterate through Class properties
You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.
For a hint, you could possibly do something like:
Record record = new Record();
PropertyInfo[] properties = typeof(Record).GetProperties();
foreach (PropertyInfo property in properties)
{
property.SetValue(record, value);
}
Where value
is the value you're wanting to write in (so from your resultItems
array).
c# - How to iterate through classes fields and set properties
public class Person
{
public string Name { get; set; }
}
public class Employee
{
public Person person = new Person();
public void DynamicallySetPersonProperty()
{
var p = GetType().GetField("person").GetValue(this);
p.GetType().GetProperty("Name").SetValue(p, "new name", null);
}
}
Iterate through all properties of a class
The answer:
var props = typeof(Animal).GetProperties().Where(prop => prop.GetSetMethod() != null);
FarmAnimal fa = new FarmAnimal();
foreach (var prop in props)
{
typeof(FarmAnimal )
.GetProperty(prop.Name,
BindingFlags.IgnoreCase |
BindingFlags.Instance |
BindingFlags.Public | BindingFlags.SetField)
.SetValue(fa,
prop.GetValue(animal));
}
How to loop through all the properties of a class?
Use Reflection:
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}
for Excel - what tools/reference item must be added to gain access to BindingFlags, as there is no "System.Reflection" entry in the list
Edit: You can also specify a BindingFlags value to type.GetProperties()
:
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);
That will restrict the returned properties to public instance properties (excluding static properties, protected properties, etc).
You don't need to specify BindingFlags.GetProperty
, you use that when calling type.InvokeMember()
to get the value of a property.
How to loop through the properties of a Class?
Something like:
object obj = new object();
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (var p in properties)
{
var myVal = p.GetValue(obj);
}
Note you need to allocate the object and pass it into the PropertyInfo.
Iterate through Nested Classes and Transform Property, Multiple Int by 2
System.RuntimeType
is the implementation of the class that represents typeof(X)
or something.GetType()
. When you pass PropertyType
to your function you are not passing the property value, but it's type.
You will need to pass the next object in the hierarchy into the recursive function by using GetValue
.
Note though that this is dangerous and error prone. For example, if you have a List<>
property you obviously cannot increase its Count
(it is readonly!). You should check to make sure that the property can be written to using the CanWrite
property.
You also need to check for null
objects. On top of that we need to handle int
differently from int?
(otherwise casting null
to int
will throw). The latter we can clean up a bit with c#7 pattern matching:
public static void ReadPropertiesRecursive(object test)
{
if (test is null) // base case
return;
var type = test.GetType();
foreach (PropertyInfo property in type.GetProperties())
{
// check if we can even read the property
if(!property.CanRead)
continue;
// use pattern matching on the value
// nulls will be ignored
// we *could* cache GetValue but then it means we will invoke it for uninteresting types/properties
// it's also why I don't call GetValue until we've inspected PropertyType
if (property.CanWrite &&
(property.PropertyType == typeof(int) || property.PropertyType == typeof(int?)) &&
property.GetValue(test) is int i)
{
property.SetValue(test, i * 2);
}
else if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
{
ReadPropertiesRecursive(property.GetValue(test));
}
}
}
An alternative version that omits some of the checks against PropertyType
can also be used. It's a bit cleaner looking but it could potentially perform the GetValue
reflection in cases where we don't need/want it (like on a double
or a struct):
public static void ReadPropertiesRecursive(object test)
{
if (test is null) // base case
return;
var type = test.GetType();
foreach (PropertyInfo property in type.GetProperties())
{
// check if we can even read the property
if(!property.CanRead)
continue;
// possibly unnecessary if not int or class
var val = property.GetValue(test);
if (property.CanWrite && val is int i)
{
property.SetValue(test, i * 2);
}
else if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
{
ReadPropertiesRecursive(val);
}
}
}
Note that you may want to have a whitelist or blacklist of types. Recursing into a Type
object for example isn't going to get you much.
Related Topics
How to I Apply Filter While Paginating in ASP.NET MVC and Entity Framework
How to Perform an Insert and Return Inserted Identity with Dapper
Do I Need to Lock or Mark as Volatile When Accessing a Simple Boolean Flag in C#
Correct Way to Get the Coredispatcher in a Windows Store App
How to Auto Resize and Adjust Form Controls with Change in Resolution
Casting Object to Int Throws Invalidcastexception in C#
How to Get Xml Node from Xdocument
Using Profiles in Automapper to Map the Same Types with Different Logic
How to Translate Cultureinfo Language Names
How to Set Web.Config File to Show Full Error Message
How to Create a New Language for Use in Visual Studio
Display Custom Error Page When File Upload Exceeds Allowed Size in ASP.NET MVC
The Source File Is Different from When the Module Was Built
How to Make a Wizard with ASP.NET MVC
How to Get a List<String> Collection of Values from App.Config in Wpf