Search

C# Classes

A class is a collection of code and is usually kept in a file with the .cs prefix. The code in a class is usually related in some way and has a common purpose. A class can contain properties, fields, events and methods.  A class is the template for an object and there can be multiple objects created from a single class and all having there own internal state.  The constructor is sometimes used to initialise the class members. 

Create a new class with a single method.

namespace MyProgram
{
    public class MyClass
    {
        public void MyMethod()
        {
            //do something.
        }
    }
}

 

Create a new object from the class called MyClass.

namespace MyProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myObject = new MyClass();
            myObject.MyMethod();
        }
    }
}

 

Constructor example.

namespace MyProgram
{
    public class MyClass
    {
        public int _firstNumber;
        public int _secondNumber;

        public MyClass(int firstNumber, int secondNumber)
        {
            _firstNumber = firstNumber;
            _secondNumber = secondNumber;
        }

        public int AddTwoNumbers()
        {
            return _firstNumber + _secondNumber;
        }
    }
}

 

Initialsing the object with a  constructor.

namespace MyProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myObject = new MyClass(5,9);
            int result = myObject.AddTwoNumbers();

            //result is equal to 14
        }
    }
}

 

2 objects created from a single class.

namespace MyProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myObject1 = new MyClass(5,9);
            int result1 = myObject1.AddTwoNumbers();

            //result1 is equal to 14

            MyClass myObject2 = new MyClass(3, 4);
            int result2 = myObject2.AddTwoNumbers();

            //result2 is equal to 7
        }
    }
}

 

Further reading Classes