Azurewrath

Hi,

I have a class like this:

public class Point2

{

private int intX;

private int intY;

public int X

{

get { return intX; }

set { intX = value; }

}

public int Y

{

get { return intY; }

set { intY = value; }

}

public Point2 (int intX, int intY)

{

this.intX = intX;

this.intY = intY;

}

public override string ToString ()

{

return String.Format ( "[{0}, {1}]", X, Y );

}

}

But I don't understand how ToString can access X and Y Aren't they properties that should be used on something like obj.X, this.X

Thanks,

aw



Re: Visual C# Language Member access question

James Curran

But I don't understand how ToString can access X and Y Aren't they properties that should be used on something like obj.X, this.X

Yes, but as a convenience, you are generally allowed to omit the "this." inside a class, unless a reference would otherwise be ambiguous (such as in your constructor).






Re: Visual C# Language Member access question

Marcelo Guerra - MSFT

Hi,

When you are inside a Class, you can use the modifier "this" to refer to the instace of the object you are in when doing something like:

public override string ToString()

{

return String.Format("[{0}, {1}]", this.X, this.Y);

}

To make life more simple the "this." can be ommited leading to the way the function is written in your code.

So if you now do:

Point2 p = new Point2(0, 0);

string s = p.ToString();

The X and Y are take from the object p.

Hope this helps.





Re: Visual C# Language Member access question

Ernst Kuschke

You can access it by accessing the properties on the instance:

public override string ToString ()

{

return String.Format ( "[{0}, {1}]", this.X, this.Y );

}


Since you're in the same class, you can also access the private storage-variables:

public override string ToString ()

{

return String.Format ( "[{0}, {1}]", intX, intY );

}







Re: Visual C# Language Member access question

Figo Fei - MSFT

Hi, Azurewrath

Yes, it can be omitted inside the class. (but when intX or intY is static member, you can not use "this", since "this" means the instance of the class)

Just remind you that we must make a difference between static members and non-static ones.

Thanks






Re: Visual C# Language Member access question

Azurewrath

Thanks all, very helpful!

aw