Sponsored Ad

Thursday, October 22, 2009

C# Public Methods

This text program is written in C # and shows how you can use public methods in one class and then call the methods outside the class. The public keyword is an accessibility modifier in C #. The default methods are private and not public, so you must specify this switch to call methods in other parts of your program. Public methods can be static, ie the kind of attached to it, or instance, that is connected to an instance of the type being built.

Program that uses public static and instance methods (C#)

using System;

public class Example
{
    static int _fieldStatic = 1; // Private static field
    int _fieldInstance = 2; // Private instance field

    public static void DoStatic()
    {
        // Public static method body.
        Console.WriteLine("DoAll called");
    }
    public static int SelectStatic()
    {
        // Public static method body with return value.
        return _fieldStatic * 2;
    }
    public void DoInstance()
    {
        // Public instance method body.
        Console.WriteLine("SelectAll called");
    }
    public int SelectInstance()
    {
        // Public instance method body with return value.
        return _fieldInstance * 2;
    }
}

class Program
{
    static void Main()
    {
        // First run the public static methods on the type.
        Example.DoStatic();
        Console.WriteLine(Example.SelectStatic());

        // Instantiate the type as an instance.
        // ... Then invoke the public instance methods.
        Example example = new Example();
        example.DoInstance();
        Console.WriteLine(example.SelectInstance());
    }
}

Output

DoAll called
2
SelectAll called
4

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers