C# and .NET interview questions - What are Extension Methods in C#.NET ?

 Posted by ArticlesMaint on 7/12/2011 | Category: C# Interview questions | Views: 13169


This is a semi-asked .NET interview question and below goes the explanation for the same.Lets say we have a simple class called as Maths and this class we have got from a 3rd party. In other words we do not have control of changing the code of this class.

public class Maths   
{
 public int Number1;
 public int Number2;
    public int Add()       
   {
     return Number1 + Number2;        
   }
}


Now let’s say we get a requirement where we need to add one more method called as subtract to the above class. As said previously you just have the DLL and you cannot go and add subtract method to the above class. One thought you can give is how about creating a new class which inherits the above and aggregates it. But let’s assume we are not given that option either. There's where we have extension methods. Extension methods enables you to "add" methods to existing classes without creating a new derived classes, recompiling, or otherwise modifying the original class. So what you can do is create static function as shown below in the below code snippet. Please note the parameter "this Maths x".

public static class MyMathExtension    

{
  Public static int Subtract(this Maths x)       
   {
      return x.Number1 - x.Number2;       
   }
}

Now when you create an object of maths class and type "." in the visual studio intellisense you should see the subtract extended method. Below is the diagram for the same. Please see the color is blue for extension methods with a down arrow symbol.



Sometimes back i was asked a very basic c# and .NET interview question What is the difference between convert.tostring and tostring (), below is a simple video which explains the concept in detail.



Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response