| title | More On Classes | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| actions |
|
||||||||
| material |
|
Tag: C# Basics
In C#, it is a common practice to implement class fields as properties with getters and setters. This chapter introduces this concept.
A class can hold many things, including variables and methods. One of the most common methods for accessing class variables are 'getters' and 'setters'.
Example:
class Square {
private int area;
public int GetArea () { return this.area; }
public int SetArea (int area) { this.area = area; }
}With these methods, the area attribute can be accessed like follows:
Square s = new Square ();
int area = s.GetArea ();
s.SetArea (0); The point of these additional methods is to to define specific rules for accessing or changing the data in an object. You may have noticed that the area variable is defined as private, which means area can only be accessed using the GetArea method, and changed using SetArea. If we now wish to limit the area of this square to within 400, we could write:
...
public int SetArea (int area) {
if (area > 400) { this.area = 400; }
else { this.area = area; }
}
...Getter and setter methods are very common in class definitions, and C# has shortcuts for declaring these methods.
The above getters and setters can be written as:
class Square {
private int area;
public int Area {
public get { return area; }
public set { area = value; }
}
}There is a further shortcut if we simply wish to get and set the area variable without any addditional rules. They can be written as:
class Square
{
public int Area { get; set; }
}This is the equivalent of declaring public getters and setters.
Also remember that when we declare Area, the variable declaration for area is not needed. In these cases, Area is also referred to as a property of Square objects. They can be accessed like this:
Square s = new Square ();
int area = s.Area; We can also add access modifiers to properties:
class Square {
public int Area { get; private set; }
}Our goal is to add some properties for the Alien class.
BigInteger is a special type of data that can represent ingeters. It is a struct, which can encapsulate multiple variables. BigInteger can be declared and initialised like below:
Note that struct is a value type, not a reference type.
BigInteger big1 = new BigInteger (10000000);
BigInteger big2 = 10000000;
ulong l = 1000000000;
BigInteger fromULong = l; Other integer types can be implicitly cast as BigIntegers.
This data type has built-in functions to convert to and from byte[], it will come in handy when we start dealing with storage later in this lesson.
- In
Alienclass, change the variables to public propertiesuint Xnaandstring AlienName. Give both properties public getters and setters; - Add a third property named
Idof typeBigInteger, with public getters and setters.