override | Overrides an inherited virtual or abstract method. |
sealed | A method that cannot be overridden by derived classes; a class that cannot be inherited by other classes. |
extern | An 'extern' method is one in which the implementation is provided elsewhere and is most commonly used to provide definitions for methods invoked using .NET interop. |
Overloading Operators
Besides overloading methods, C# also supports the overloading of operators (such as +
, -
, /
, and *
). Operator overloading allows you to provide your own operator implementation for your specific type. To see how operator overloading works, consider the following program containing the Point class representing a point in a coordinate system:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OperatorOverloading {
class Program {
static void Main(string[] args) {}
}
}
The Point
class contains two public properties (X
and Y
), a constructor, and a method — DistanceFromOrigin()
.
If you constantly perform calculations where you need to add the distances of two points (from the origin), your code may look like this:
static void Main(string[] args) {
}
A much better implementation is to overload the +
operator for use with the Point
class. To overload the +
operator, define a public static operator within the Point
class as follows:
class Point {
public Single X { get; set; }
public Single Y { get; set; }
public Point(Single X, Single Y) {
this.X = X;
this.Y = Y;
}
public double DistanceFromOrigin() {
return (Math.Sqrt(Math.Pow(this.X, 2) + Math.Pow(this.Y, 2)));
}
}
The operator
keyword overloads a built-in operator. In this example, the overloaded +
operator allows it to 'add' two Point
objects by adding the result of their DistanceFromOrigin()
methods:
static void Main(string[] args) {
Point ptA = new Point(4, 5);
Point ptB = new Point(2, 7);
}
You can also use the operator
keyword to define a conversion operator, as the following example shows:
class Point {
public Single X { get; set; }
public Single Y { get; set; }
public Point(Single X, Single Y) {
this.X = X;
this.Y = Y;
}
public double DistanceFromOrigin() {
return (Math.Sqrt(Math.Pow(this.X, 2) + Math.Pow(this.Y, 2)));