Assigning an int to a struct object without using unsafe

I have a struct definition in c# as follows

public struct test                                                                                  
{
    byte   SetCommonPOP;
    byte   SetCommonSVP;
    byte   SetCommonUHDP;
    byte   SetCommonMHDP;
};

How do I assign an int y to an object x of this structure without having to use unsafe?

Jon Skeet
people
quotationmark

You could write a custom conversion operator:

public struct Test
{
    private readonly byte pop;
    private readonly byte svp;
    private readonly byte uhdp;
    private readonly byte mhdp;

    // TODO: Properties to return the above

    public Test(byte pop, byte svp, byte uhdp, byte mhdp)
    {
        this.pop = pop;
        this.svp = svp;
        this.uhdp = uhdp;
        this.mhdp = mhdp;
    }

    public static implicit operator Test(int value)
    {
        // Working from most significant to least significant bits...
        byte mhdp = (byte) ((value >> 0) & 0xff);
        byte uhdp = (byte) ((value >> 8) & 0xff);
        byte svp = (byte) ((value >> 16) & 0xff);
        byte pop = (byte) ((value >> 24) & 0xff);
        return new Test(pop, svp, uhdp, mhdp);
    }
}

Personally I'd prefer a static FromInt32 method instead of an implicit operator, but that's your call. It's very possible that you don't need all the & 0xff parts in the conversion - and I wouldn't bother with them if you were using a uint instead of an int. Extracting parts of a signed integer just makes me twitchy, and this is possibly overcompensation. Another alternative would be a cast of value to a uint as a local variable to start with.

people

See more on this question at Stackoverflow