Introduction to C#
Let's take a look at my notes on Object-Oriented 0rogramming (OOP) in C#.
Classes
Class structure:
public class ClassName // access modifier, class definition
{ // class body
public int num1; // fields: class level variables
public string string1;
public void Method() // methods
{
Console.WriteLine("Hello!");
}
}
Class may also contain events and properties.
Classes are a reference type.
Access modifiers
public: accessible from outside
private: only accessible from within the class
protected: only accessible from within the class and its inheriters
internal: not accessible to other project within the solution
Example:
internal class Employee
{
public string firstName;
public string lastName;
public string email;
public int numberofHoursWorked;
public double wage;
public double hourlyRate;
const int minHoursWorked = 1;
public DateTime birthDay;
public void PerformWork()
{
PerformWork(minHoursWorked);
//numberofHoursWorked++;
//Console.WriteLine($"{firstName} {lastName} has worked for {numberofHoursWorked}.");
}
public void PerformWork(int numberofHours)
{
numberofHoursWorked += numberofHours;
Console.WriteLine($"{firstName} {lastName} has worked for {numberofHours}.");
}
public double ReceiveWage(bool resetHours = true)
{
wage = numberofHoursWorked * hourlyRate;
Console.WriteLine($"{firstName} {lastName} has received £{wage} for {numberofHoursWorked} hours.");
if (resetHours)
{
numberofHoursWorked = 0;
}
return wage;
}
public void DisplayEmployeeDetails()
{
Console.WriteLine($"First name: \t{firstName} \nLast name: \t{lastName} has received £{wage} for {numberofHoursWorked} hours.");
}
}
Constructor
When we instantiate an object a constructor
method is called.
Constructors can be custom or deafult - a default one will be called if a constractor is
not specified. However, once we create a custom constructos, the default one is no
longer available.
A constructor doesn't have a return type and it shares its name with the name of the
class.
W use a constructor to set the initial values for the fields.
public class Employee
{
public string firstName;
public int age;
public Employee(string name, int ageInt)
{
firstName = name;
age = ageInt;
}
}
We can also use primary constructor which has been introduced with C# 12.
public class Employee(string name, int ageInt)
{
}
Just like mothods, constructors can also be overloaded, if we give each a different set of parameters.
public Employee(string first, string last, string em, DateTime bd) : this(first, last, em, bd, 0)
{ } //4 parameters
public Employee(string first, string last, string em, DateTime bd, double rate)
{ // 5 parameters
firstName = first;
lastName = last;
email = em;
hourlyRate = rate;
birthDay = bd;
}
Creating an instance of a class
An instance of a class is called an object. We create a new instance of a class with the new operator.
Let's create an object of a class from the example above.
We will use the construvtor in order to do that.
Employee employee = new Employee("Lena", 55);
variable type | variable name = new (class ← it can be omitted) | arguments
Let's invoke a method on the created Employee.
employee.PerformWork();
Let's change a field.
employee.firstName = "Magdalena";
Let's return a value from a method.
int salary = employee.ReceiveWage();
Roll dice example:
Random dice = new Random();
OR (in the later versions of .NET Runtime)
Random dice = new();
Some methods require you to create an instance of a class before you call them.
This line would cause an error:
int roll = Random.Next();
To get rid of this error, we need to create an instance of the Random class (before accessing the Next() method).
Random dice = new();
int roll = dice.Next(1, 7);
Console.WriteLine(roll);
// random int between 1 and 6
Properties
Properties are a way to access the data encapsulated inside of a class.
Certain values that has been set inside of a class (ex. tax rate or event date) should be protected - we should only be able to use these values, but not change them. In order to do that we need to set the access modifier of a particular variable as private, then create a Property "wrapping" that variable in order to make its value accessible from the outside.
Properties should be capitalized.
Inside of a class:
private string firstName;
public string FirstName
{
get
{
// code that returns the value of the field
return firstName;
}
set
{
// logic that sets the value firstName
firstName = value;
}
}
Inheritance (Is-A relationship)
Inheritance is a concept where a class gets data and functionality from a parent class.
Public members declared on the parent class are accessible to the child class.
Private members declared on the parent class are not.
Protected members declared on the parent class are accessible to the child class, but for any other classes their behaviour remains privete.
public class Parent { }
public class ChildInheritingFromParent: Parent { }
Composition (Has-A relationship)
Composition combines existing classes creating more complex classes. This promotes code reuse and has multiple benefits.
Polymorphism - virtual and override
Polymorphism allows to override the base class method with a new implementation.
The base class needs to indicate that classes inheriting from it can give a method a different implementation by adding the keyword virtual.
If the inheriting class wants to use a base class' method and modify it, the keyword override nedds to be used.
public class Parent
{
public virtual void Method() {...}
}
public class ChildInheritingFromParent: Parent
{
public override void Method() {...}
}
Interfaces
At first glance an interface might look like a class, but there are major differences between these two types.
An interface usually starts with "I".
Classes that implement an interface must include all variables and methods specified on thet interface.
Interfaces cannot be instantiated with the new keyword.
Let's have a look at an example of an interface:
public interface IStudent
{
void Study();
int Revise();
}
Now let's see how to implement this interface:
public void Person: IStudent
{
public void Study() {...}
public int Revise() {...}
}
Using Polymorphism with Interfaces
IStudent student = new Person();
student.Study();
Sources:
https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp
https://learn.microsoft.com/en-gb/training/modules/csharp-call-methods/3-call-methods
Comments (0)
Be the first to leave a comment