.NET Daily

C# Extension Methods

Introduction

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.


LATEST POSTS

My View of a JIRA Workflow for Web Development 17th April, 2018

How To Solve: SQL Server detected a logical consistency-based I/O error: invalid protection option. 19th March, 2018

C#

C# Extension Methods

Posted on .

What are Extension Methods?

“Extension Methods” is a brand new feature released in C# 3.0 and in short terms they are static methods that can be invoked using the instance method syntax. Mainly this functionality was introduced to extend the functionality of standard query operators from Linq but it also can be used to extend the base C# types with custom methods.

How to make use of Extension Methods?

Let’s say you have a bunch of string utility methods that manipulates the string values in your project. For sure every project has that StringUtility class :). What if you could add those methods right into the Intellisense menu of string’s extended methods and properties?

For example, let’s add to the string type a new method that concatenates the existing value and add an ellipsis(… ) at the end of it.

Please take a look at the code made for the scenario above:

Step 1). Create a new class where you want to put the methods that will extend your string type. I have created a Business folder inside my solution and I added the following class:

Please make sure that the class and the method is static and the string parameter from the method has “this” keyword.

Step 2). In the page you want to use the extension methods, add a namespace to the class you’ve created above. Ex:

Step 3). Make use of the extension method! Ex:

Extension Methods

Extension Methods

That’s all! The result for the string above should look like this on the page:

“Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam adipiscing pharetra mi, eu vestibulum…”

Note: You can use extension methods only if you work with c# 3.0 and above.

Download the demo application: [download id=”9″ format=”1″]

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.

Comments
  • user

    AUTHOR jensen

    Posted on 7:37 am April 15, 2016.
    Reply

    what extension would u put for the following: drop down list, radio button, radio button list and a file upload???

  • View Comments (0) ...
    Navigation