Total Pageviews

Tuesday, September 25, 2012

Introduction to Classes


Classes




Classes are declared by using the keyword class followed by the class name and a set of class members surrounded by curly braces. Everyclass has a constructor, which is called automatically any time an instance of a class is created. The purpose of constructors is to initialize classmembers when an instance of the class is created. Constructors do not have return values and always have the same name as the class
Listing 7-1. Example C# Classes: Classes.cs

// Namespace Declarationusing System;// helper classclass OutputClass
{
    string myString;
    // Constructor
    public OutputClass(string inputString)
    {
        myString = inputString;
    }

    // Instance Method
    public void printString()
    {
        Console.WriteLine("{0}", myString);
    }

    // Destructor
    ~OutputClass()
    {
        // Some resource cleanup routines    }
}
// Program start classclass ExampleClass
{
    // Main begins program execution.    public static void Main()
    {
        // Instance of OutputClass        OutputClass outCl = new OutputClass("This is printed by the output class.");
        // Call Output class' method
        outCl.printString();
    }
}

No comments:

Post a Comment