Lecture overview -- Keyboard shortcut: 'u'  Previous page: Parameter Arrays -- Keyboard shortcut: 'p'  Next page: Methods versus Properties versus Indexers -- Keyboard shortcut: 'n'  Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Textbook -- Keyboard shortcut: 'v'  Help page about these notes  Alphabetic index  Course home  Page 28 : 29
Object-oriented Programming in C#
Data Access, Properties, and Methods
Extension Methods

Have you ever wanted to add a new method to an existing class, without defining a subclass? If so, extension methods - as introduced in C# 3.0 - is the solution to your problem.

In C# 3.0 an extension method defines an instance method in an existing class without altering the definition of the class.

 

/user/normark/oop-csharp-1/sources/c-sharp/point/point-representation-independence/version2/Client-v1.csMotivation: A Client of Point without use of DistanceTo.


/user/normark/oop-csharp-1/sources/c-sharp/csharp-3/extension-methods/Client.csA Client of class Point which uses an extension method DistanceTo. This program is explained

The method DistanceTo is used as an instance method in this program...

/user/normark/oop-csharp-1/sources/c-sharp/csharp-3/extension-methods/PointExtensions.csThe static class PointExtensions. This program is explained

... but actually implemented as a (somewhat special) static method in the static class PointExtensions.

  • An extension method

    • extends the type of the first parameter

    • is defined as a static method with a this modifier on the first parameter

    • must be defined in a static class

    • cannot access private instance variables in the extended class

    • is called by - behind the scene - translating to a call of the static method

Go to exerciseExtending struct Double