Extension Methods in C# – An Introduction

Sathish Nadarajan
 
Solution Architect
July 9, 2016
 
Rate this article
 
Views
5000

Though it is very late to discuss about the Extension methods, but I feel that before diving into PNP (Patterns and Practices), it is worth to know about the Extension methods and how to write that.

As all of us know, the Extension Methods are similar to the normal methods, but a custom one. i.e., the default classes and the custom classes will have a set of methods. Along with that, if we want to add some more methods, Extension Methods are very useful.

In practical scenario, in the last article, about the console application, we saw the password needs to be converted as a SecureString class. In that demo, I have written that method as an Ordinary method. Now, let us convert the same into Extension Method.

Let me create a new class in the same namespace.

 namespace Console.Office365
 {
     public static class StringExtensionMethods
     {
         public static SecureString ToSecureString(this string Source)
         {
             if (string.IsNullOrWhiteSpace(Source))
                 return null;
             else
             {
                 SecureString Result = new SecureString();
                 foreach (char c in Source.ToCharArray())
                     Result.AppendChar(c);
                 return Result;
             }
         }
     }
 }
 
 

Now, from the Main Console, we can call the method as,

 string password = "***********";
 var secure = password.ToSecureString();
 
 

Like this we can have extension methods for all the default classes and custom classes as well.

 

Download the Source HERE

 

 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment