Reputation: 3515
I have two classes with exact type properties but with different property names. So I want to copy every property to corresponding property which resides in different class.
For example
public class ClassOne
{
public string Name {get; set;}
public string Code {get; set;}
public UserMode Mode {get; set;}
public enum UserMode {A=1, B=2, C=3};
}
public class ClassTwo
{
public string MyName {get; set;}
public string MyCode {get; set;}
public MyUserMode Mode {get; set;}
public enum MyUserMode MyMode {AA=1, BB=2, CC=3};
}
Since this only cross on my mind I created Helper method which converts ClassOne To ClassTwo taking every member and copy it's values like
public static ClassTwo(ClassOne one)
{
var two = new ClassTwo()
{
MyName = one.Name,
MyCode = one.Code,
// how to copy enum value ??
};
}
Question is: How can I copy enums like I did above with Name and Code?
Thanks
Upvotes: 2
Views: 8165
Reputation: 22794
Just cast it to an int
and then to the new enum:
public static ClassTwo(ClassOne one)
{
var two = new ClassTwo()
{
Name = one.Name,
Code = one.Code,
Mode = (ClassTwo.MyUserMode)((int)one.Mode);
};
}
This is assuming that both enums have the exact same int
values.
A safer way to do this would be using Enum.IsDefined
:
public static ClassTwo(ClassOne one)
{
var mode = (ClassTwo.MyUserMode)((int)one.Mode);
if (!Enum.IsDefined(typeof(ClassTwo.MyUserMode), mode)
throw new InvalidOperationException("Cannot map enums.");
var two = new ClassTwo()
{
Name = one.Name,
Code = one.Code,
Mode = mode
};
}
Upvotes: 9