Skip to content

Instantly share code, notes, and snippets.

@ForNeVeR
Last active April 25, 2022 15:22
Show Gist options
  • Save ForNeVeR/d539b99e0b734c44473df38746723d77 to your computer and use it in GitHub Desktop.
Save ForNeVeR/d539b99e0b734c44473df38746723d77 to your computer and use it in GitHub Desktop.
A showcase of union in C#. Ha-ha.
using System;
using System.Runtime.InteropServices;
namespace ConsoleApp77
{
class User
{
public string Name { get; set; }
public string Surname { get; set; }
public string Password { get; set; }
}
class UserDTO
{
public string Name { get; set; }
public string Surname { get; set; }
}
[StructLayout(LayoutKind.Explicit)]
struct MyDuck
{
[FieldOffset(0)]
public User User;
[FieldOffset(0)]
public UserDTO UserDTO;
}
class Program
{
static void Main(string[] args)
{
var user = new User
{
Name = "Vassily",
Surname = "Poopkeen",
Password = "12345"
};
var duck = new MyDuck
{
User = user
};
UserDTO dto = duck.UserDTO; // works! :D
Console.WriteLine(dto.Name); // Vassily
Console.WriteLine(dto.GetType()); // ConsoleApp77.User ?!
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment