Search code examples
c#listobjectidentifier

Getting object name from list


Is there a way to retrieve the name of an object stored in a list?

What I want to do is to add an object name - the name of matrix in this particular case - prior to printing out properties of that matrix.

internal class Program
{
    private static void Main(string[] args)
    {
        //Create a collection to help iterate later
        List<Matrix> list_matrix = new List<Matrix>();

        //Test if all overloads work as they should.
        Matrix mat01 = new Matrix();
        list_matrix.Add(mat01);

        Matrix mat02 = new Matrix(3);
        list_matrix.Add(mat02);

        Matrix mat03 = new Matrix(2, 3);
        list_matrix.Add(mat03);

        Matrix mat04 = new Matrix(new[,] { { 1, 1, 3, }, { 4, 5, 6 } });
        list_matrix.Add(mat04);

        //Test if all methods work as they should.     
        foreach (Matrix mat in list_matrix) 
        {
            //Invoking counter of rows & columns
            //HERE IS what I need - instead of XXXX there should be mat01, mat02...
            Console.WriteLine("Matrix XXXX has {0} Rows and {1} Columns", mat.countRows(), mat.countColumns()); 
        }
    }
}

In short I need here

Console.WriteLine("Matrix XXXX has {0} Rows and {1} Columns",
                  mat.countRows(),
                  mat.countColumns());

a method to write out name of that particular object - matrix.


Solution

  • Variable name as property

    You can't retrieve the object reference name you 'once used' to declare the matrix. The best alternative I can think of is adding a string property Name to the Matrix and set it with the appropriate value.

        Matrix mat01 = new Matrix();
        mat01.Name = "mat01";
        list_matrix.Add(mat01);
    
        Matrix mat02 = new Matrix(3);
        mat02.Name = "mat02";
        list_matrix.Add(mat02);
    

    That way you'd be able to output the names of the matrices

    foreach (Matrix mat in list_matrix)
    {
        Console.WriteLine("Matrix {0} has {1} Rows and {2} Columns", 
            mat.Name, 
            mat.countRows(), 
            mat.countColumns());
    }
    

    Alternative using Lambda expression

    As mentioned by Bryan Crosby, there IS a way to get the variable name in code using lambda expressions, explained in this post. Here a small unit test that shows how you could apply it in your code.

        [Test]
        public void CreateMatrix()
        {
            var matrixVariableName = new Matrix(new [,] {{1, 2, 3,}, {1, 2, 3}});
            Assert.AreEqual("matrixVariableName", GetVariableName(() => matrixVariableName));
        }
    
        static string GetVariableName<T>(Expression<Func<T>> expr)
        {
            var body = (MemberExpression)expr.Body;
    
            return body.Member.Name;
        }
    

    PS: do note his warning about performance penalties.