Jump to content

union and struct in C#

- - - - -

  • Please log in to reply
3 replies to this topic

#1
irancplusplus

irancplusplus

    Learning Programmer

  • Members
  • PipPipPip
  • 65 posts
Hi
what is most similar to this C++ code in C#:


int main()

{

	union

	{

		unsigned a;

		struct

		{

			unsigned short x;

			unsigned short y;

		};

	};

	a = 12345678;

	cout<< x;

        cout<< y;	

}

I looking for an equivalent code for union and struct in C#.
I wrote this ebook! Will you translate it into English for free!?:confused: PM me!

#2
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
I googled this page off of MSDN's documentation site:
How to: Create a C/C++ Union Using Attributes (C#)
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#3
lespauled

lespauled

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 231 posts
  • Programming Language:C, C++, C#, JavaScript, PL/SQL, Delphi/Object Pascal, Visual Basic .NET, Pascal, Transact-SQL, Bash
C# doesn't have support for C/C++ unions. But, you can use StructLayout(LayoutKind.Explicit) and FieldOffset attributes to create equivalent functionality.

How to: Create a C/C++ Union Using Attributes (C#)

#4
kernelcoder

kernelcoder

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 288 posts
  • Location:Dhaka
  • Programming Language:C, Java, C++, C#, Visual Basic .NET
  • Learning:Objective-C, PHP, Python, Delphi/Object Pascal
Yes, so the equivalent code in C# will be like as follows....


[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)]
struct TestUnion
{
    [System.Runtime.InteropServices.FieldOffset(0)]
    public uint a;

    [System.Runtime.InteropServices.FieldOffset(0)]
    public ushort x;

    [System.Runtime.InteropServices.FieldOffset(2)]
    public ushort y;
}

And here is the usage...

TestUnion uni = new TestUnion();
uni.x = 10;
uni.y = 1;

Can you guess what is the value of a? This is a homework for you: Tell me what is the value of a?




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users