0

Is there a way to get the name of an explicit interface property backing field?

For example, for:

public interface I
{
    string PPPP { get; }
}

public class C: I
{
    private string _other_field = default!; // random private field, just to fill.
    public string S => _s_backing; // random property, just to fill.

    private string _s_backing = default!;
    string I.PPPP => _s_backing; // <--- looking for this one!
}

For property PPPP I'm looking to figure up the string "_s_backing".

I mean. Is there a way to create this helper:

Helpers.DoSomeReflectionMagic( typeof(C), "PPPP" ) 
// I expect, it returns: `_s_backing`.

What I tried: I was digging into typeof(C) properties, but I didn't find the backing field anywhere. Maybe there is no way to get it.


The underlying XY problem:

public interface ITree<T>
{
    T? Parent { get; }
    IEnumerable<T> Children { get; }
}

public class Category: ITree<Category>
{
    public string Name { get; set; }
    public Category? MyParentCategory { get; set; }
    public IEnumerable<Category> MySubCategories { get; set; }

    // Implementing interface
    Category? ITree<Category>.Parent => MyParentCategory;;
    IEnumerable<Category> ITree<Category>.Children => MySubCategories;
}

// dbcontext with fluent api to configure model blah blah

public static class DbContextTreeExtensions
{
    public static IEnumerable<T> GetRoots<T>(this MyDbContext ctx)
    {
        var backingfieldname =  // <-- The Y problem
            Helpers
            .DoSomeReflectionMagic(typeof(T), "Parent");

        return
            ctx
            .Set<T>()
            .Where(q => EF.Property<T?>(q, backingfieldname) == null)
            .AsEnumerable();
    }
}

I would like to do:

var ctx = MyDbContextFactory.NewContext();
var mainCategories = ctx.GetRoots<Category>();
dani herrera
  • 48,760
  • 8
  • 117
  • 177
  • https://stackoverflow.com/questions/95910/find-a-private-field-with-reflection – Roman Ryzhiy Nov 30 '22 at 12:22
  • 4
    The property getter can contain any arbitrary code. You cannot just assume that it returns a field. If you know the name `_s_backing`, you can get the `FieldInfo` of that, but that's it. – Sweeper Nov 30 '22 at 12:25
  • @Sweeper, is what I suspected. Can you post your comment as answer? – dani herrera Nov 30 '22 at 12:28
  • 5
    I posted it as a comment because I didn't really say anything too useful... Perhaps this is an [XY problem](https://xyproblem.info) and you can explain what you're ultimately trying to do, so I can potentially post a more useful answer? – Sweeper Nov 30 '22 at 12:33
  • @Sweeper, you are clever, bro. I posted the X problem on Q. (just a minimal example) – dani herrera Nov 30 '22 at 14:02

0 Answers0