0

Is there any equivalent to this C Code or someway to get some sort of similar behaviour in the C# ?

typedef union RGBQUAD
{
    DWORD rgb;
    struct{
        BYTE b;
        BYTE g;
        BYTE r;
        BYTE unused;
    };
};
DBYTES
  • 17
  • 4
  • 1
    [MS answer](https://social.msdn.microsoft.com/Forums/en-US/60150e7b-665a-49a2-8e2e-2097986142f3/c-equivalent-to-c-quotunionquot?forum=csharplanguage) – STerliakov Jun 15 '22 at 09:24
  • and why you need union at all ? you can just use struct with 4 bytes ... or an array of 4 bytes ... or an unsigned 4-byte integer to interop this – Selvin Jun 15 '22 at 09:26
  • Why not using `Color` struct in c#? (the only difference is that `unused` corresponds to `Alpha` in `Color`) https://learn.microsoft.com/en-us/dotnet/api/system.drawing.color?view=net-6.0 – Dmitry Bychenko Jun 15 '22 at 09:31

2 Answers2

0

In general case you can use StructLayout attribute

using System.Runtime.InteropServices

...

// If fields are in correct order
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct rgb {
  public byte b;
  public byte g;
  public byte r;
  public byte unused;
};

or FieldOffset attribute to provide offsets for each field:

[StructLayout(LayoutKind.Explicit)]
struct rgb {
  [FieldOffset(0)]
  public byte b;
  [FieldOffset(1)]
  public byte g;
  [FieldOffset(2)]
  public byte r;
  [FieldOffset(3)]
  public byte unused;
};

In your particular case (ARGB color) you may want System.Drawing.Color struct.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

I think the closest you can get to this is with the use of the dynamic type in this where you can use as many types as you want in one variable. It's slower of course as it uses reflection and the classes/struct have to be public but it does come close

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic

public class Program
{
    public struct COLORREF
    {
        public byte a,b,c;
    }
    
    public struct RGB
    {
        public byte a,b,c;
    }
    
    public static void Main()
    {           
        dynamic d = 10;
        Console.WriteLine(d);
        d = 10.5;
        Console.WriteLine(d);
        
        d = new COLORREF { a = 1, b = 2, c = 3};        
        Console.WriteLine(d.a);
        
        d = new RGB { a = 1, b = 2, c = 3};
        Console.WriteLine(d.c);
        
    }
}
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98