C# Classes

Classes in C# are created using the keyword class. Usually you also declare classes in a namespace, but this is not obligatory. In fact to declare a class, all you need at the minimum is the class keyword, some curly brackets to contain whatever code and data you want to put in the class (which may none at all) and of course, a name for the class, which by convention starts with an uppercase letter.

[Looking for online 1-to-1 C# classes? email me: john@caveofprogramming.com]






Here's an example of a simple class in C#. In fact this is a complete program, because it contains the standard main method which is called by the operating system to run the program.

The class also contains a constructor (a method with the same name as the class and no return type, which is run automatically when objects are created from the class) and a single public method.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        // Constructor -- called automatically
        // when the class is constructed.
        Program()
        {
            Console.WriteLine("Constructor called!");
        }

        // A "method"
        public void Speak()
        {
            Console.WriteLine("Speak method called!");
        }

        // Main method: called automatically
        // by the operating system.
        static void Main(string[] args)
        {
            // Create a new program object.
            Program program = new Program();

            // Call the 'speak' method
            program.Speak();

            // Wait for a key press before closing
            // the console window
            Console.ReadKey();
        }
    }
}




Note that in the main method we create an actual instance of the class (in other words, we create an object of this class) and call its Speak method.

The main method is declared static, meaning that it can be called without any object of the class being present; it can be called using the class itself. If we want to call instance (non static) methods of the class, we must create an object from the class first. It might seem strange to do this within the static main method of the class itself, but this is perfectly normal and acceptable.