user1765862
user1765862

Reputation: 14145

copy values from enums in different namespaces

I have two classes MyObj and MyObjDTO both have a matchin enum property StarRating.

public class MyObj
{
    public enum StarRating {
         One = 1,
         Two = 2
    }
}

public class MyObjDTO
{
    public enum StarRating {
         One = 1,
         Two = 2
    }
}

I want to assign value from MyObjDTO to MyObj. I tried

var dto = ... loaded dto object

var data = new MyObj
            {
                ...
                RatingStatus = (int)dto.RatingStatus
            };

But It doesn't work, I'm getting underlined error under int and simple

 RatingStatus = dto.RatingStatus

doesn't work either.

Upvotes: 2

Views: 443

Answers (3)

Jamie Ide
Jamie Ide

Reputation: 49261

You can direct cast because the underlying type is int. However, you should ensure that the values are identical in both enums or refactor as Darin suggests.

public enum StarRating1
{
    One = 1,
    Two = 2
}

public enum StarRating2
{
    One = StarRating1.One,
    Two = StarRating1.Two
}

var sr1 = StarRating1.One;
var sr2 = (StarRating2) sr1;

Upvotes: 0

Koopakiller
Koopakiller

Reputation: 2884

Your StarRating type is not a property - it is type more accurate a enumeration.

I think the simpliest way is to convert the value to an int and then to the expected type:

RatingStatus = (MyObj.StarRating)(int)dto.RatingStatus

But I recommend to use only one StarRating enum at both places.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

You're gonna be casting like hell in order to do this perversion:

var data = new MyObj
{
    RatingStatus = (MyObj.StarRating)(int)dto.RatingStatus,
};

So you should really refactor your code and reuse this StarRating enumeration instead of duplicating it in both classes as you currently have.

Upvotes: 4

Related Questions