0

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?

2
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by ddanbe
Featured Replies
  • 1
    ddanbe 2,525   6 Years Ago

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

  • 1
    ddanbe 2,525   6 Years Ago

    You got it indeed :) Happy programming! Read More

0

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;
        //}
    }
1

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.

Comments
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"

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.