Get the name of an object in C #

2

Can I get the name with which I have instantiated an object and save it in a string?

     float[] objeto1 = new float[4];
     float[] objeto2 = new float[5];
     new Vectores().MejoresAlumnos(objeto1 , objeto2);

     class Vectores
        {               
            public string MejoresAlumnos(float[] notas1, float[] notas2)
                {
                   this.notas1 = notas1;
                   this.notas2 = notas2;
                   return notas1.Length > notas2.Length ? notas1.ToString() : notas2.ToString();
                }
    }

Evidently with the .toString() it is not possible to do it but ... Is there any way to get it?

I would like to be able to receive the name of the parameter that happened to the MejoresAlumnos method, that is, in this simple example I would like to receive a string with the value of objeto2

    
asked by Edulon 02.11.2017 в 18:41
source

1 answer

2

This returns the name of the local variable within the same method.

static void Main(string[] args)
{
    float[] objeto1 = new float[4];
    float[] objeto2 = new float[5];
    Console.WriteLine(GetName(()=>objeto1));
}

static string GetName<T>(Expression<Func<T>> expr)
{
    return ((MemberExpression)expr.Body).Member.Name;
}

Print:

  

object1

If you have C # 6.0 or higher, reach with

Console.Write(nameof(objeto1));
    
answered by 02.11.2017 / 20:07
source