Tuesday, August 28, 2012

Deep copy of C# object properties

Sometimes you have two different class types with the same properties and you want to copy all the property values from one to the other.

One way is to simply hand code one assignment statement for each field they have in common.

Another option is to use an open source mapping library like AutoMapper

Still other times you might find yourself in the middle ground of not wanting to hand code all the assignments and also not wanting to deal with a 3rd party library.

Here is an example of how you can roll your own automapper in a few lines of code.  This snippet copies like-named properties from a source to a target.  It recurses on any properies that don't have a type starting with "System." and it ignores source properties with value of null.

Friday, August 17, 2012

How do mixins work in C#?

Extension methods which target a common marker interface can be viewed as partial implementations of that interface.

If you place such extension methods in different namespaces then it is possible to utilize a technique of "Mixing In" the implementations used by a class.

This is demonstrated in code below.  The one part of this that I took a minute to get my head around was that ILogger loses the semantics of an interface.  The methods available to it are those extension methods which are visible to the compiler as dictated by the using statements.

Some links I learned from before writing this: