0

Assuming I have a class MyDto that will be mapped like this:

public class MyDto
{
    public string PropertyA { get; }

    public int PropertyB { get; }

    public bool PropertyC { get; }
}

public class MyMapper
{
    public MyResult Map(MyDto objectToMap) => 
        new MyResult { Bla = objectToMap.PropertyA, Blub = objectToMap.PropertyC };
}

As you can see, MyMapper only uses PropertyA and PropertyC, but not PropertyB. How can I resolve this programmatically?

Or in other words: how can I determine all property references of MyDto like this:

var namesOfUsedProperties = typeof(MyDto).FindAllPropertyReferences();
namesOfUsedProperties.Should().Contain("PropertyA", "PropertyC");
namesOfUsedProperties.ShouldNot().Contain("PropertyB");

Thank you!

PS: I'm using C# 11 and .NET 7.

mu88
  • 4,156
  • 1
  • 23
  • 47
  • 1
    You cannot, at least not using reflection. Main reason: The number of clients is unknown, as a public class can be referenced from other assemblies you don't know about. – PMF May 15 '23 at 06:59
  • 1
    @thehennyy That solution fails to mention that it only works if you know the assemblies in question. And that it is terribly slow. – PMF May 15 '23 at 07:01
  • U can Use Automapper And ignore It with =>>>> CreateMap().ForMember(x => x.Blarg, opt => opt.Ignore()); – sep7696 May 15 '23 at 07:04
  • Isn't one of the reasons you map objects in the first place, that you do not have to always map all properties? – Fildor May 15 '23 at 07:27
  • @thehennyy It looked promising, but unfortunately, it finds no references when applied to my code. – mu88 May 15 '23 at 07:35
  • @mu88 For me the code in the referenced question works with your use case. I changed the search to `var token = typeof(MyDto).GetProperty("PropertyC").GetGetMethod().MetadataToken;` The output is `MyMapper::Map: 0x14`. Maybe you have to change the assemblies to search through or just search within all currently loaded assemblies. Also as mentioned in the comments, you have to check if the execution time is within your budget. – thehennyy May 15 '23 at 08:22

0 Answers0