Skip to content

Instantly share code, notes, and snippets.

@khellang
Last active July 28, 2016 10:58
Show Gist options
  • Save khellang/4995e730a91e53281edce7623436203b to your computer and use it in GitHub Desktop.
Save khellang/4995e730a91e53281edce7623436203b to your computer and use it in GitHub Desktop.
Assign to a getter-only auto property
using System;
using System.Reflection;
public static class Program
{
public static void Main()
{
var test = new T();
var testType = test.GetType();
var property = testType.GetProperty("Test");
FieldInfo backingField;
if (!property.CanWrite && property.TryGetBackingField(out backingField))
{
backingField.SetValue(test, "It's working!");
}
Console.WriteLine(test.Test);
}
private static bool TryGetBackingField(this PropertyInfo property, out FieldInfo field)
{
var declaringType = property.DeclaringType;
if (declaringType == null)
{
field = null;
return false;
}
field = declaringType.GetField($"<{property.Name}>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance);
return field != null;
}
private class T
{
public string Test { get; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment