Tuesday, January 14, 2014

C# method extension

when you don't have code with you to edit certain library and want you to and some functionality.

I have Assembly called log and it has a class LogAction it has following functions
     

  1.        public  void WriteLog (LogType logtype)      
  2.        public  void WriteLog(LogType logtype, string Message)

let's assume we want to add third function called 
  • WriteLogWithException(LogType logtype,  Exception exc)
Add reference  to your project



then create static class like below


using System;
using LogLibrary; // here i call my library
namespace MethodExtension
{
    public static class Extension
    {
        public static void WriteLogWithException(this LogAction logaction, LogType logtype,  Exception exc)
        {
            logaction.WriteLog(logtype,exc.Message);
           
        }
    }
}
here we want two things to memorize extension class should be static and the method  you wish to write should be also static. 
You must specify the this keyword before the appropriate parameter you want the method to be called upon.

thank you.. :)
       

1 comment: