CSharp/C# Tutorial - C# Methods






A method performs an action in a series of statements.

A method can have parameters and a return type.

A method can specify a void return type, which indicates that it doesn't return any value to its caller.

A method can also output data back to the caller via ref/out parameters.

A method's signature must be unique within the type.

A method's signature comprises its name and parameter types.

Methods allow the following modifiers:

NameModifier
Static modifierstatic
Access modifierspublic internal private protected
Inheritance modifiersnew virtual abstract override sealed
Partial method modifierpartial
Unmanaged code modifiersunsafe extern




Overloading methods

A type may overload methods, as long as the signatures are different.

For example, the following methods can all coexist in the same type:


void myMethod (int x) {...} 
void myMethod (double x) {...} 
void myMethod (int x, float y) {...} 
void myMethod (float x, int y) {...} 

The return type and the params modifier are not part of a method's signature.

Pass-by-value versus pass-by-reference

Whether a parameter is pass-by-value or pass-by-reference is also part of the signature.

For example, myMethod(int) can coexist with either myMethod(ref int) or myMethod(out int).

However, myMethod(ref int) and myMethod(out int) cannot coexist:


void myMethod (int x) {...} 
void myMethod (ref int x) {...} // OK so far 
void myMethod (out int x) {...} // Compile-time error 





Finalizers

Finalizers are class-only methods that execute before the garbage collector reclaims the memory for an unreferenced object.

The syntax for a finalizer is the name of the class prefixed with the ~ symbol:


class Class1 {
   ~Class1() {
      ... 
   }
}

Finalizers allow the following modifier:

ItemModifier
Unmanaged code modifierunsafe

Partial Types and Methods

Partial types allow a type definition to be split-typically across multiple files.

For example:


// MyClassGen.cs - auto-generated 
partial class MyClass { ... } 


// MyClass.cs - hand-authored 
partial class MyClass { ... }