C
C#2mo ago
Nothavid

✅ Finding all FieldInfo's of BackingFields of a type

I have following code snippet to find all FieldInfo's of a type t which are BackingFields of public properties of type double.
FieldInfo[] doubleFields = t
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.PropertyType == typeof(double))
.Select(p => t.GetField($"<{p.Name}>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance)!)
.Where(f => f is not null)
.ToArray();
FieldInfo[] doubleFields = t
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.PropertyType == typeof(double))
.Select(p => t.GetField($"<{p.Name}>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance)!)
.Where(f => f is not null)
.ToArray();
I was now wondering if the CompilerGeneratedAttribute is only applied to BackingFields or if there are other instances of fields having that attribute since I cannot currently think of any. If it is only applied to BackingFields, I could skip the step of getting all properties.
2 Replies
Nothavid
Nothavid2mo ago
I just had the bright idea of asking ChatGPT the exact same and, for once, it actually knew something. Now that I've seen it it's obvious but compiler generated fields are also created when you use async or yield return. $close
MODiX
MODiX2mo ago
If you have no further questions, please use /close to mark the forum thread as answered