0

So,I have a class student and I created a reference variable pointing to the object of class student.I want to get the name of the reference variable in my code.I want o/p as Harry(which is my reference variable).Is this thing possible?

Code:

   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

        namespace ConsoleApplication1
        {
            class Program
            {
                static void Main(string[] args)
                {
                    student harry = new student();
                    //OUTPUT:harry
                }
            }

            public class student { }
        }
Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Ajay
  • 643
  • 2
  • 10
  • 27

2 Answers2

1

Better use a public property than a field and and do it like this:

//Class

public class Student { public string Name { get; set; }}

//Instantiate class method 1:

Student harry = new Student() {Name = "Harry"};

//Instantiate class method 2:

Student harry = new Student();
harry.Name="Harry";


//get property output:


Console.WriteLine(harry.Name);
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
1

No there is not a way to do this. You can only access data that are stored in a class.

What you can do is to compare references e.g.

 if( otherStudent == student ) {  } 

In this case you test weather the variable otherStudent points to the same object as the variable student points to.

Trifon
  • 1,081
  • 9
  • 19