This is what i have as part of my code:

class Pawn : Pieces
{
    string name;
  

    
    public Pawn(string piece)
    {
        this.name = piece;
    }


    public override string pieceName()
    {
        return this.name;
    }

Now in the method pieceName, i am not sure what effect there will be if i put just return name...
Basically, after i have already used this.variable... do i need to keep using the same variable with this or not?

Recommended Answers

All 5 Replies

Depends, here you may use it freely or not.The word refers to the Pawn object.
It is sometimes needed to avoid name conflicts with other equily named variables.
But best is to use a property here:

class Pawn : Pieces
    {
        string name;


        public Pawn(string piece)
        {
            this.name = piece;
        }

        // the Name property can be used like
        // Pawn.Name = "B2"; or
        // string piece = Pawn.Name;
        public string Name 
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        //public override string pieceName()
        //{
        //    return this.name;
        //}
    }

i wanted to know , conceptually, what is the difference if i use this.name for the first time and name throughout the code and if i use this.name and then this.name throughout the code

As I said already, in your example name and this.name refer to the same field in a Pawn object. So it does not matter here. Personaly I prefer to use the this.name syntax, so in a large class I can tell that name is a field belonging(in the scope of) the Pawn class.

commented: Thank you +0

alright, i think i got it. There is no difference, once i use this.name.. i can use name outside the constructor without the identifier "this"

You got it indeed :)
Happy programming!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.