Can ReSharper generate code that copies properties from one object to another?
It's really easy. ReSharper doesn't do it, but you can use a super duper REGEX!
In Visual Studio:
public string Email { get; set; }
public string CellPhone { get; set; }
public int NumChildren { get; set; }
public DateTime BirthDate { get; set; }
Select all your properties. Hit CTRL-D to copy down.
Now hit CTRL-H to replace. Make sure
.*
is selected for Regex matching.Replace:
public [\w?]* (\w*) .*
(This Regex may need to be tweaked)With:
dest.$1 = source.$1;
Now you have some beautiful code you can put in a method of your choosing:
dest.Email = source.Email;
dest.CellPhone = source.CellPhone;
dest.NumChildren = source.NumChildren;
dest.BirthDate = source.BirthDate;
EDIT: New alternatives
- You can use AutoMapper for dynamic runtime mapping.
- Mapping Generator is really nice for static mapping. It can generate the code above and it works well with R#.
This is somewhat derivative from answer by @Jess (his regex didn't work for me on VS2013) but instead of using Visual Studio
I am using regex101
Click link above and just paste your properties into Test string
field and you will get them mapped.
Regex I used
public [A-Za-z\?]* ([A-Za-z0-9]*) .*
and replace
Dest.$1 = Source.$1
hope this saves you some time.
I don't believe Resharper can do this, but Open Source AutoMapper can. New to AutoMapper? Check out the Getting Started page.
I agree with @Ben Griswold.
In most situations, Automapper is the way to go.
But when you truly want to generate code that copies properties from one object to another, try this:
- Create a brand new class and derive from the class from which you want to copy properties.
- Right-click on this new derived class and click 'Refactor > Extract Interface'.
- Check all properties that you wish to copy.
- Choose 'Place beside' because this interface will be only temporary.
- Click 'Next'.
- Modify your derived class so that you are no longer inheriting from the base class and you are only implementing your new interface. Expect to see a red squiggle.
- Place your cursor over the red squiggle and hit 'ALT-ENTER' to 'Implement Members'.
- Click 'Finish'.
- Delete that temporary interface and modify your class so that you are no longer implementing it.