How to: Call a Method on an Object

This example calls an instance method, myMethod, referenced through an instance of the class.

Example

class Program
{
    static void Main(string[] args)
    {
        Program myObject = new Program();
        myObject.myMethod();
    }
    void myMethod()
    {
        // Do something
    }
}

Compiling the Code

Copy the code, and paste it into a console application and build the solution.

Robust Programming

Use the fully qualified name of the method, unless it is accessible from the same scope.

If the method is static, you should not reference it through an instance of the class.

When assigning an expression to a property, make sure of the following:

  • That it is of a compatible data type.

  • That it has a valid value, especially if the value is derived from user input.

See Also

Other Resources

Visual C# Express