Posts

Automatic Mappings with AutoMapper

Introduction Dispite recent announcements  by Jimmy Bogard , I'm still using AutoMapper . Maybe it's because I'm used to it and I think it has great features - like mapping LINQ expressions - anyway, I'm sticking to it, for the time being! A couple things, though, I feel are missing: The ability to automatically map types Dependency injection (DI) of services into  Profile classes So I set out to make these both work! Fortunately,  AutoMapper  provides many extension points that we can hook to in order to do what we want. So, I'm going to talk a bit about these topics. In a nutshell, the problem I am to solve is: automatically map types from one assembly into the types in another one, of course, using only conventions. My approach was, use a custom mapper profile ( Profile ) to go through all types in the source assembly, find out the corresponding types in the target assembly, and add them to the maps. AutoMapper and Dependency Injection First things first.  ...

C# Magical Syntax

Introduction This post is an update to an old one on my  old blog  and it was inspired by my latest posts on C# versus Java . You may not have realized that some of the patterns that you’ve been using for ages in your C# programs are based on conventions, rather than on a specific API. What I mean by this is, some constructs in C# are based on some magical methods with well-defined names which are not defined in any base class or interface, but yet just work. Let’s see what they are. Enumerating Collections You are probably used to iterating through collections using the foreach statement. If you are, you may know that foreach actually wraps a call to a method called GetEnumerator , like the one that is defined by the IEnumerable and IEnumerable<T> interfaces. Thus, you might think, the magic occurs because the collection implements one or the two, but you would be wrong: it turns out that in order to iterate through a class using foreach all it takes is that the c...

Java vs C# - Part 2

Introduction This is part two of a series of posts on Java and C#, the first part is available here . This time, I am going to talk about a lot of things that weren’t covered before, and leave some stuff for future posts! I'm covering: Object and collection initialization Casts Methods Operator overloading Attributes/annotations Exceptions Iterations Returning enumerables Lambda functions Expression trees Auto closing blocks Object and Collection Initialization C# offers an interesting syntax for initializing instance properties at the same time a variable is declared, which can be combined with parameterized constructors: MyClass c = new MyClass( "constructor argument" ){ OneProperty = 1, AnotherProperty = "two" }; It also offers a syntax for defining the values of a collection upon declaration, including dictionaries (indexed collections): var list1 = new List< string > { "A" , "B" , "C" }; List< string > list2 = [...