C# and OOP Flashcards
Printing a line
Console.WriteLine(iValue);
Converting number to string
string strValue = floatValue.ToString();
Casting float to int
int iValue = (int)fValue;
(rounds down)
Converting string to number
string strValue = “13.8”;
float fValue = float.Parse(strValue);
Getting a substring of a string
string.Substring(a, b) gives you the b characters which come after character a
“vge1974”.Substring(2, 4) = “e197”
Conditional statement
if (condition)
{
code
}
else
{
more code
}
Comparison operators
==, !=, <, >, <=, >=
Logical operators
&&, ||, !
“true”, “false”
Expressing x^y
Math.Pow(x, y)
While loop
while (condition)
{
code
}
(can control flow using “break” and “continue”)
Do while loop
do
{
code
}
while (condition)
For loop
for (setup; condition; increment)
{
code
}
Foreach loop
foreach (<type> currentItem in listOfItems)
{
code
}</type>
What is OOP?
A programming framework that facilitates the reuse and extensibility of code. Bits of source code with relevant purposes are grouped together as classes, managed as a hierarchy with inheritance. Objects are instances of a class, which is like a blueprint.
Advantages of OOP
With OOP, source code becomes easier to maintain and follow
Code can be reused through inheritance, improving efficiency and productivity
Security through encapsulation
Drawing classes in UML
Attributes
———–
Methods
The constructor is always there but not listed
Drawing the main program itself in UML
Attributes
———–
Methods
Creating a new object using the constructor
Cow cowName = new Cow(“Moo”, 8);
What is method overloading?
When a method has different declarations for different types of input
What are static functions and variables?
Ones which belong to the class, rather than the instances of the class (the objects). They are usually used to denote functions/variables that are the same across all objects of that class. They can be called without creating an object of such a class. They have to be changed from the class, not the object.
They are underlined in UML.
Example of using a static variable
Student s1 = new Student();
s1.studentName = “Henry”;
Console.WriteLine(s1.studentName); // instance variable
Console.WriteLine(Student.universityName); // static variable
What is encapsulation and why is it useful?
This is where a class keeps all relevant information, but only exposes necessary information to other classes.
Issues avoided by encapsulation: human errors, intentional attacks, classes which are difficult to follow
public vs private vs protected
public: accessible everywhere
private: accessible only within the same class
protected: accessible only within the same class AND child classes
Old encapsulation method using setters and getters
public class Cow
{
private float _fWeight;
private string _strName;
public void SetFWeight(float fWeightIn) { if (fWeightIn > 0.0f) _fWeight = fWeightIn; } public float GetFWeight() { return _fWeight; } }