Q:

PostSharp's LocationInterceptionAspect doesn't work with structs

I made a BitsAspect to simulate C++ bit-fields, which applied this way:
[StructLayout(LayoutKind.Explicit)]
class Class {
    [FieldOffset(0)] public byte Whole;
    [FieldOffset(0)] [BitsAspect(0,0)] public byte Bit0;
    [FieldOffset(0)] [BitsAspect(1,1)] public byte Bit1;
}

It works great, but only on classes. On structs it just doesn't work:
[StructLayout(LayoutKind.Explicit)]
struct Struct {
    [FieldOffset(0)] public byte Whole;
    [FieldOffset(0)] [BitsAspect(0,0)] public byte Bit0;
    [FieldOffset(0)] [BitsAspect(0,1)] public byte Bit1;
}

Here is the test:
[TestMethod]
public void BitOperations_Test() {
    var c = new Class();
    c.Bit1 = 1;
    Assert.AreEqual(2, c.Whole);
    Assert.AreEqual(1, c.Bit1);

    // all assertions pass to this point.

    var s = new Struct();
    s.Bit1 = 1;
    Assert.AreEqual(2, s.Whole); // fails: s.Whole is 1 :-(
    Assert.AreEqual(1, s.Bit1);
}

The aspect:
[Serializable]
[MulticastAttributeUsage(MulticastTargets.Property | MulticastTargets.Field)]
public class BitsAspect : LocationInterceptionAspect {
    private ulong _mask;
    private Type _type;
    public int BitOffset { get; private set; }
    public int BitsCount { get; private set; }

    public BitsAspect(int bitOffset, int bitsCount) {
        BitOffset = bitOffset;
        BitsCount = bitsCount;
    }

    public override void CompileTimeInitialize(LocationInfo targetLocation, AspectInfo aspectInfo) {
        _type = targetLocation.LocationType;
        if (_type.IsEnum) _type = _type.GetEnumUnderlyingType();
        ulong mask = ((ulong) 1 << BitsCount) - 1;
        _mask = mask << BitOffset;
        base.CompileTimeInitialize(targetLocation, aspectInfo);
    }

    public override void OnGetValue(LocationInterceptionArgs args) {
        var @this = args.Instance;
        var oldValue = Convert.ToUInt64(args.Binding.GetValue(ref @this, Arguments.Empty));
        var value = (oldValue & _mask) >> BitOffset;
        var converted = Convert.ChangeType(value, _type);
        args.Value = converted;
    }
    public override void OnSetValue(LocationInterceptionArgs args) {
        var @this = args.Instance;

        var newValue = Convert.ToUInt64(args.Value);
        var oldValue = Convert.ToUInt64(args.Binding.GetValue(ref @this, Arguments.Empty));

        var value = (oldValue & ~_mask) | (newValue << BitOffset);
        var converted = Convert.ChangeType(value, _type);
        args.SetNewValue(converted);
    }
}

Any way I can achieve this with the value-type structs too?

A:

LocationInterceptionAspect on struct should work without any problem here.
Declaration of Bit1 is a little bit different for Class:
[FieldOffset(0)] [BitsAspect(1,1)] public byte Bit1;

and for Struct:
[FieldOffset(0)] [BitsAspect(0,1)] public byte Bit1;

I would bet that it makes the difference.
Beware mutable value types, they can be the pure evil.

