C# / .NETDevOpsMisc
C# / .NET
C# Reflection
Alexandru Puiu
Alexandru Puiu
September 16, 2012
1 min

C# Reflection copy every property of a class to another class with the same properties.

Let’s say you have to copy all the values of the properties of a class to another (maybe larger) class, but there’s no inheritance between them. You can achieve this using reflection very simply.

foreach (var prop in item.GetType().GetProperties())
{
    var p2 = outputModel.GetType().GetProperty(prop.Name);
    p2.SetValue(outputModel, prop.GetValue(item, null), null);
}

Tags

utils
Alexandru Puiu

Alexandru Puiu

Engineer / Security Architect

Systems Engineering advocate, Software Engineer, Security Architect / Researcher, SQL/NoSQL DBA, and Certified Scrum Master with a passion for Distributed Systems, AI and IoT..

Expertise

.NET
RavenDB
Kubernetes

Social Media

githubtwitterwebsite

Related Posts

RavenDB Integration Testing
Using RavenDB in Integration Testing
December 24, 2022
2 min

Subscribe To My Newsletter

I'll only send worthwhile content I think you'll want, less than once a month, and promise to never spam or sell your information!
© 2023, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media