C Sharp

Access to Class Members

The last point I'll make about static methods is the rule governing which class members can be accessed from a static method. As you might imagine, a static method can access any static member within the class, but it cannot access an instance member. This is illustrated in the following code: -

using System;
class SQLServerDb
{
    static string progressString1 = "repairing database...";
    string progressString2 = "repairing database...";
    public static void RepairDatabase()
    {
        Console.WriteLine(progressString1); // This will work.
        Console.WriteLine(progressString2); // Fails compilation.
    }
}
class StaticMethod3App
{
    public static void Main()
    {
        SQLServerDb.RepairDatabase();
    }
}

Summary

Methods give classes their behavioral characteristics and carry actions out on our behalf. Methods in C# are flexible, allowing for the return of multiple values, overloading, and variable parameters. The ref and out keywords allow a method to return more than a single value to the caller. Overloading allows multiple methods with the same name to function differently, depending on the types and/or number of arguments passed to them. Methods can take variable parameters. The params keyword allows you to deal with methods where the number of arguments isn't known until run time. Virtual methods allow you to control how methods are modified in inherited classes. Finally, the static keyword allows for methods that exist as part of a class rather than as part of an object.

by BrainBellupdated
Advertisement: