top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is extension method in c# and how to use them?

0 votes
227 views
What is extension method in c# and how to use them?
posted Mar 28, 2017 by Amit Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Another cool feature of C# 3.0 is Extension Methods. They allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type. For instance, you might like to know whether a certain string was a number or not. The usual approach would be to define a function and then call it each time, and once you got a whole lot of those kind of functions, you would put them together in a utility class, like this:

public class MyUtils
{
    public static bool IsNumeric(string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

Now you could check a string by executing a line of code like this:

string test = "4";
if (MyUtils.IsNumeric(test))
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");

However, with Extension Methods, you can actually extend the String class to support this directly. You do it by defining a static class, with a set of static methods that will be your library of extension methods. Here is an example:

public static class MyExtensionMethods
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

The only thing that separates this from any other static method, is the "this" keyword in the parameter section of the method. It tells the compiler that this is an extension method for the string class, and that's actually all you need to create an extension method. Now, you can call the IsNumeric() method directly on strings, like this:

string test = "4";
if (test.IsNumeric())
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");
answer Mar 29, 2017 by Shivaranjini
Similar Questions
+4 votes

Is it possible to override this method? if yes then how can we achieve it?

+3 votes

By-default all the methods & variables in class are private.

In C#.net Main() method is private then how compiler access this Main() Method out side the class because compiler is not part of our program then how compiler access this Main() method?

Here we loose our data abstraction property ? Can anyone put some light on it?

...