get & set

// Using properties, get & set keywords
//=====================================

class Point
{
int myX; // myX is private
int myY; // myY is private

public int x
{
get
{
return myX;
}
set
{
myX = value;
}
}

public int y
{
get
{
return myY;
}
set
{
myY = value;
}
}
}

class PropApp
{
public static void Main()
{
Point starting = new Point();
Point ending = new Point();

starting.x = 1;
starting.y = 4;
ending.x = 10;
ending.y = 11;

System.Console.WriteLine("Point 1: ({0},{1})", starting.x, starting.y);
System.Console.WriteLine("Point 2: ({0},{1})", ending.x, ending.y);
}
}

Can someone please help me to understand what's gong on with everything above the class PropApp? Thanks

Comments

  • The class above that is just a class that has properties which you can assign and read. It's pretty generic/standard way of setting up a class with a few properties, what exactly do you want explained in more detail?
    Divergence Hosting Technical Blog
  • This is insane to read without indentation:
    [code]class Point
    {
    int myX; // myX is private
    int myY; // myY is private

    public int x
    {
    get
    {
    return myX;
    }
    set
    {
    myX = value;
    }
    }

    public int y
    {
    get
    {
    return myY;
    }
    set
    {
    myY = value;
    }
    }
    }[/code]

    Yes what you are seeing is a very basic class. If you were to refer to this in your code you would access it like so...

    Point pt = new Point();
    pt.x = 10;
    pt.y = 10;

    When you are defining a "Property" on a class you have to give the compiler code telling it how to "get" a value from the property and code telling it how to "set" the property to a value.

    Both the "get" and "set" blocks contained in the property declaration are nothing more than executable methods that fire either when a value is being pulled from or pushed to the property.

    pt.x = 10; is pushing a value to the "x" property and will fire the "set" method.

    int m = pt.x; is pulling a value from the "x" property and will fire the "get" method (which expects an integer value to be returned in this case)

    the "set" method of a property will always be passed data matching the property's type that can be accessed with the "value" keyword.

    Now in dotnet you can actually get rid of half of this code by using "auto properties". Your compiler will actually recognise the following code:

    [code]public class Point
    {
    public int X { get; set; }
    public int Y { get; set; }
    }[/code]

    Your compiler will effectively treat these properties as if they were simply variables.

    ><//~Psightoplasm`~
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories