Page 1 of 1

Making a class in C#

PostPosted: 16 Jun 2013, 12:16
by joppiesaus
hey! I am bored so here a example for a class in C#

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 :)

Re: Making a class in C#

PostPosted: 16 Jun 2013, 15:34
by ismellike
That's a really nice tutorial; I've only started using these classes, and I wish I would've earlier. It makes things a lot easier to read and to make.

Re: Making a class in C#

PostPosted: 16 Jun 2013, 15:48
by lucasds12
Wow, what a completely nice, valid explaining and a useful tutorial. Joppie, it seems you involved in #C which makes me proud. Excellent work and good job!
-Lucas

Re: Making a class in C#

PostPosted: 16 Jun 2013, 19:04
by joppiesaus
Thanks people! I though about that too. When I coded first, I didn't know about voids, I just coded everything twice or something :P

EDIT: I totaly forgot about this:

if you want to set strings / ints / bools etc manually, or get it(without methods), you can do like so:
Code: Select all
public string name {get; set;}

Re: Making a class in C#

PostPosted: 16 Jun 2013, 19:24
by Conor
This is great <ok>