0

In this case i Want to print m2k: salt:2 skill: is there a way to do that?
to somehow get the name of the object that we are using

namespace practice
{
class SmashPlayer
{
    private int salt, skill;
    public SmashPlayer(int salt, int skill)
    {
        this.salt = salt;
        this.skill = skill;
    }
public void print()
    {
        Console.WriteLine("{0}'s\nsalt:{1}\nskill:{2}",Name of object,salt,skill);
    }

}
class Program
{

    public static void Main(string[] arg)
    {



        SmashPlayer m2k = new SmashPlayer(2,5);
        m2k.print();

    } 
  }
}
SuperMinefudge
  • 301
  • 3
  • 11
  • 2
    http://stackoverflow.com/questions/72121/finding-the-variable-name-passed-to-a-function-in-c-sharp gives you some options to achieve exactly what you've asked. Note that usually you would not use variable name for anything that can be displayed to user - depending on your actual goals there are more traditional solutions (starting with just adding `Name` property). – Alexei Levenkov Dec 10 '16 at 21:56

2 Answers2

2

You cannot do that. You need to pass string to the constructor.

SmashPlayer m2k = new SmashPlayer (2, 5, "m2k");

Of course you need to add new parameter to that constructor and save it in instance field.

To avoid refactoring issues, you can use nameof operator.

SmashPlayer m2k = new SmashPlayer (2, 5, nameof (m2k));
apocalypse
  • 5,764
  • 9
  • 47
  • 95
  • what are refactoring issues? – SuperMinefudge Dec 10 '16 at 22:12
  • @SuperMinefudge: For example it's when you rename your `m2k` variable to `newName`, and you will forget to update "m2k" string passed to the constructor. But if you use `nameof` operator - refactoring tool will be aware of that, and will also change `nameof(m2k)` to `nameof(newName)`. – apocalypse Dec 10 '16 at 22:17
2

It's not really possible. Simple example:

SmashPlayer m2k = new SmashPlayer(2,5);
SmashPlayer m2k_again = m2k;

Two variables, but it's the same instance of the class, what should you write as variable name? m2k or m2k_again ?

Look on answer of apocalypse for a possible solution. https://stackoverflow.com/a/41080725/5281555

Community
  • 1
  • 1
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49