Defining Methods

Methods use standard function format, along with accessibility and optional static modifiers

Example

using System;

namespace ConsoleApplication1
{
    class MyClass
    {
        public string GetString()
        {
            return "hello methods.";
        }
    }
}

Remember that if you use the static keyword, then this method is accessible only through the class, not the object instance. You can also use the following keywords with method definitions:

virtual The method may be overridden.
abstract The method must be overridden in non – abstract derived classes (only permitted in abstract classes).
override The method overrides a base class method (it must be used if a method is being overridden).
extern The method definition is found elsewhere.

Example (method override)

using System;

namespace ConsoleApplication1
{
    public class MyBaseClass
    {
        public virtual void DoSomething()
        {
            // Base implementation.
        }
    }
    public class MyDerivedClass : MyBaseClass
    {
        public override void DoSomething()
        {
            // Derived class implementation, 
            //overrides base implementation.
        }
    }
}

If override is used, then sealed may also be used to specify that no further modifications can be made to this method in derived classes — that is, the method can ’ t be overridden by derived classes.

Example

using System;

namespace ConsoleApplication1
{
    public class MyDerivedClass : MyBaseClass
    {
        public override sealed void DoSomething()
        {
            // Derived class implementation, 
            //overrides base implementation.
        }
    }
}

Using extern enables you to provide the implementation of a method externally to the project.