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();

    } 
  }
}
1
  • 2
    stackoverflow.com/questions/72121/… 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). Commented Dec 10, 2016 at 21:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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));

2 Comments

what are refactoring issues?
@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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.