A class needs a constructor. You can make it without arguments:
- Code: Select all
using System;
public class Motorcycle
{
public string nameOfCycle;
public Motorcycle()
{
}
}
Or with arguments:
- Code: Select all
using System;
public class Motorcycle
{
public string nameOfCycle;
public Motorcycle(string cycleName)
{
nameOfCycle = cycleName;
}
}
Of course, we want some method groups for the cycle! For example speed:
- Code: Select all
using System;
public class Motorcycle
{
public string nameOfCycle;
public int speedOfCycle;
public Motorcycle(string cycleName)
{
nameOfCycle = cycleName;
speedOfCycle = null;
}
public void speed(int speed)
{
speedOfCycle = speed;
}
}
Now we have a class for a motorcycle!
To use it, we do this:
- Code: Select all
Motorcycle myMotorcycle = new Motorcycle("Harley abcd1234");
The name of the cycle will now be Harley abcd1234, you can call that string like so:
- Code: Select all
string cycleName = myMotorcycle.nameOfCycle;
Now we want to know the speed!
- Code: Select all
int cycleSpeed = myMotorcycle.speedOfCycle;
But wait... this will throw null! We didn't defined the speed yet!
so:
- Code: Select all
myMotorcycle.speed(100);
if we call it now, it will return 100!
You can do various of tricks with this, for example:
- Code: Select all
Console.Writeline("My motorcycle can reach speeds over " + myMotorcycle.speedOfCycle.ToString() + " km/u! And the name of my motorcycle is " + myMotorcycle.nameOfCycle + "!");
So that's explained! Hopefully it is clear now