Last active
July 28, 2016 10:58
-
-
Save khellang/4995e730a91e53281edce7623436203b to your computer and use it in GitHub Desktop.
Assign to a getter-only auto property
This file contains hidden or 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.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