Using Extension methods to create mapper classes

suggest change

We can create a better mapper classes with extension methods, Suppose if i have some DTO classes like

public class UserDTO
 {
        public AddressDTO Address { get; set; }
 }

 public class AddressDTO
 {
        public string Name { get; set; }
 }

and i need to map to corresponding view model classes

public class UserViewModel
{
    public AddressViewModel Address { get; set; }
}

public class AddressViewModel
{
    public string Name { get; set; }
}

then I can create my mapper class like below

public static class ViewModelMapper
{
      public static UserViewModel ToViewModel(this UserDTO user)
      {
            return user == null ?
                null :
                new UserViewModel()
                {
                    Address = user.Address.ToViewModel()
                    // Job = user.Job.ToViewModel(),
                    // Contact = user.Contact.ToViewModel() .. and so on
                };
      }

      public static AddressViewModel ToViewModel(this AddressDTO userAddr)
      {
            return userAddr == null ?
                null :
                new AddressViewModel()
                {
                    Name = userAddr.Name
                };
      }
}

Then finally i can invoke my mapper like below

UserDTO userDTOObj = new UserDTO() {
        Address = new AddressDTO() {
            Name = "Address of the user"
        }
    };

UserViewModel user = userDTOObj.ToViewModel(); // My DTO mapped to Viewmodel

The beauty here is all the mapping method have a common name (ToViewModel) and we can reuse it several ways

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Extension Methods:
* Using Extension methods to create mapper classes

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
47 Extension Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script