Last active
April 25, 2022 15:22
-
-
Save ForNeVeR/d539b99e0b734c44473df38746723d77 to your computer and use it in GitHub Desktop.
A showcase of union in C#. Ha-ha.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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