dimanche 17 octobre 2021

Getting property name from within property type

I couldn't figure out how to formulate the title any better. I see quite a few posts with similar titles but which discuss entirely different stuff.

So here we go. The actual on-ground situation is complex, but I'll try to post an absolute minimalistic example to describe it.

Let's say we have a class named Animal:

class Animal
{
  public void Run()
  {
    try
    {
      //try running
    }
    catch(Exception e)
    {
      MessageBox.Show(this.SomeCleverWayOfGettingPropertyName() + " failed to run");
    }
  }
}

Now I define several properties of Animal type in another class:

class Zoo
{
  public Animal Zebra {get; set;}
  public Animal Lion {get; set;}
  public Animal Rhino {get; set;}

  public void RunAll()
  {
    Zebra.Run();
    Lion.Run();
    Rhino.Run();
  }
}

What do I write in place of SomeCleverWayOfGettingPropertyName() to let it show name of the animal (that is name of the declared property), like "Zebra failed to run".

As I said, the actual situation is more complex, so kindly avoid answers like, "why don't you redesign your entire code base and instead try X". My hope is to find something in System.Reflection to find out the calling member's name, but I haven't found anything like that yet.





Aucun commentaire:

Enregistrer un commentaire