Skip to content

Instantly share code, notes, and snippets.

@Konard
Last active January 3, 2022 13:50
Show Gist options
  • Save Konard/c62453978f5cca1fc48b44f74050fd80 to your computer and use it in GitHub Desktop.
Save Konard/c62453978f5cca1fc48b44f74050fd80 to your computer and use it in GitHub Desktop.
Methods of structs cannot be used as delegates. The struct is copied in the process of delegate creation, and therefore there is no way to get mutuable struct updated in this case. https://replit.com/@Konard/StructMethodCannotBeUsedAsDelegate
$ dotnet run
StructSetter result before: 0
StructSetter result after: 0
ClassSetter result before: 0
ClassSetter result after: 42
using System;
struct StructSetter
{
public int Result;
public void Set(int value) => Result = value;
}
class ClassSetter
{
public int Result;
public void Set(int value) => Result = value;
}
class Program
{
static void UseSetter(Action<int> action)
{
action(42);
}
public static void Main (string[] args)
{
StructSetter structSetter = new StructSetter();
Console.WriteLine($"StructSetter result before: {structSetter.Result}");
UseSetter(structSetter.Set);
Console.WriteLine($"StructSetter result after: {structSetter.Result}");
ClassSetter сlassSetter = new ClassSetter();
Console.WriteLine($"ClassSetter result before: {сlassSetter.Result}");
UseSetter(сlassSetter.Set);
Console.WriteLine($"ClassSetter result after: {сlassSetter.Result}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment