Saturday, 19 April 2014

Beginner's C# Course, Part 2

The basics of C#: Constructors and Classes

What is a constructor?
A Constructor is a special method that you must always have in a class. It is the method used to create an instance of the class.

But what does all this mean? What are instances?
Well, whenever you make a variable, you must instantiate it.
For example.

int i;

This creates an int32 variable, but does not instantiate it.
It does not equal 0, it equals null.
If I then do

i = 0;

It is now instantiated as an int32, it has used int32's constructor method.

So how can this knowledge be used?
Well, let's say, for example, we wanted to make a "Student" class.

##File Start##
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//These are some default using statements put in whenever you make a new class

namespace ExampleProgram
//Here's our namespace
{
    class Student
    //Here's our class
    {
        public Student(string name, int age)
        {
        //And here's our constructor
        //This constructor method requires a string variable and an int variable
        }
    }
}
##File End##

This class doesn't actually DO anything yet, but it's a great example of both constructors and method arguments (The string and int required)

So to instantiate this class, we would do something like this:

Student pupil1 = new Student("Billy", 12);

This creates an instance of the Student class, where the name is Billy, and the age is 12. It then stores the instance in a variable called pupil1.

And that's it for constructors.

On Monday I'll be doing something a little different. Part one of a source code series, where I will simply share the source of a project I'm working on. I'll be doing this every third session, to appeal to those who already understand the basics.

So make sure to check back on Wednesday when we will be discussing Properties and fields within classes.

No comments:

Post a Comment