Extension Methods in C# - An Introduction


Sathish Nadarajan
SharePoint MVP
Published On :   09 Jul 2016
Visit Count
Today :  1    Total :   3311
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

Sharegate: Kick-Ass Tool
Think Your SharePoint & Office 365 Are Secure ? Find Out Now!


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.

SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Categories

Migratiin Tools for SharePoint