Fall 2020
September 12, 2020
new (to create an object), return (to send a value back from a method), private (to prevent access to the attributes from the “outside world”), public (to allow using the methods from the “outside world”).UML is a specification language with multiple benefits:
A class is represented as follows:
| ClassName |
|---|
- attribute: int |
+ SetAttribute(attributeParameter: int): void |
+ GetAttribute(): int |
Note that void is optionnal. For our Rectangle class, this gives:
| Rectangle |
|---|
- width: int |
- length: int |
+ SetLength(lengthParameter : int): void |
+ GetLength(): int |
+ Setwidth(widthParameter: int): void |
+ GetWidth(): int |
+ ComputeArea(): int |
Last time, in lab, you were asked to write additional methods. They look like this:
public int ComputePerimeter()
{
return length*2 + width*2;
}
public void DoubleRectangle()
{
width *= 2;
length *= 2;
}
public void Swap()
{
int temp;
temp = length;
length = width;
width = temp;
}We could also write a method that multiply the length and width of a rectangle by a particular factor given in argument:
Note that this method is more general than DoubleRectangle, which can be “emulated” using MultiplyRectangle(2).
A variable exists at a particular time and place in a program, that defines its scope.
You cannot use a variable before declaring it! The following would return an error:
Rectangle.cs’s variables are not directly accessible in Program.cs (you have to use accessors).Identifiers can be uniformly renamed.
is the same as
We will use this example to discuss the scope:
MyClass, attribute, SetAttribute and attributeParameter can be changed, those are the identifiers in this class.
We can change all the identifiers in the classes if we want: class names, method names, etc. But it’s good to have conventions.
“Hard” convention:
Variations / Conventions for instances variables and argument names:
mAttributes or _AttributesSetAttributes(int aAttribute), or (int value)A constant is a variable whose value cannot change.
const int MONTHS = 12;
const double AVOGADRO = 6.0220e23; // Avogadro Number. Units 1/mol
const double PI = 3.14159265358979;
const double MILES_TO_KM = 1.60934;For instance, π is defined in the Math class and can be accessed as follows:
We can use interpolation to display more nicely numerical values. There are four important format specifiers in C#.
| Format specifier | Description |
|---|---|
| N or n | Formats the string with a thousands separator and a default of two decimal places. |
| E or e | Formats the number using scientific notation with a default of six decimal places. |
| C or c | Formats the string as currency. Displays an appropriate currency symbol ($ in the U.S.) next to the number. Separates digits with an appropriate separator character (comma in the U.S.) and sets the number of decimal places to two by default. |
| P or p | Print percentage |