vendredi 23 octobre 2020

Get the declared variable name in a class in C#

I want to do something like this - where I capture the original declaring objects variable name inside the object.

 public class Foo
    {
        private string _originalDeclarer;
        
        public Foo(string originalDeclarer=nameof(this))
        {
            _originalDeclarer = originalDeclarer;
        }

        public string OriginalDeclarer
        {
            get => _originalDeclarer;
            set => _originalDeclarer = value;
        }
    }

    public static class Bar
    {
        public static void CreateFoos()
        {
            Foo GreenFoo = new Foo();
            Foo BlueFoo = new Foo();
            
            Console.WriteLine(GreenFoo);
            Console.WriteLine(BlueFoo);
            
            //Expected output
            // "GreenFoo"
            // "BlueFoo"
        }    
    }

The above understandably doesn't work, and I understand that variable names are not stored in runtime metadata, so the general answer to this question is that it cannot be done.

That said, research leads me to several workarounds, and I am looking for the best one.

This question does a good job with the proposal:

class Self
{
    public string Name { get; }

    public Self([CallerMemberName] string name = null)
    {
        this.Name = name;
    }
}

Then:

class Foo
{
    private Self me = new Self(); // Equivalent to new Self("me")

    public void SomeMethod()
    {
        // Can't use the default here, as it would be "SomeMethod".
        // But we can use nameof...
        var joe = new Self(nameof(joe));
    }
}

I've yet to test the above if it works, but the drawback would be problematic for me.

I have - but struggling to find an earlier answer I found to this question where the names where substituted at compile time.

If anyone has ways around this problem (even if it horrifically slow) or knows how the compile-time substitution I would be very interested.

The above propose workaround would work for me if I could stop instantiation inside a method.





Aucun commentaire:

Enregistrer un commentaire