none
Use of extension method. RRS feed

  • Question

  • I would like to know use of extension method in real time scenario. if anybody has used in any real time scenario or in any circumstances. Can anybody guide me, where can ir be useful.

    Best regards

    Mrutyunjaya

    Tuesday, February 5, 2019 5:12 AM

Answers

  • We use it to add many methods to System.String, such as:

    	public static string StripWhiteSpace(this string expression)
    	{
    		return expression.Trim().Replace(" ", "");
    	}

    Then it can be called as if it were a regular string method:

    string strippedString = someString.StripWhiteSpace();



    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter



    Tuesday, February 5, 2019 3:56 PM

All replies

  • it provides a way to extend the existing types behavior without modifying the existing class. It's useful where we don't have access to a type's code and we want some extended behavior on it. One example is we use an extension method which is called on datatable instance and converts it to List. the calling is like:

    var list = dataTable.ToList<MyDTO>();

    Another real example is the linq method like Select  and Where as an example are extension methods which we can call on instance of any collection of type IEnumerable<T> , the methods are not part of the type itself originally but are extension added to it for it's usefulness.


    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, February 5, 2019 5:39 AM
  • Hello,

    Checkout my GitHub repository on language extensions and Microsoft TechNet article.

    Here are two examples, the first is a generic extension method Between, note how it works against int and DateTime. The second is a utility extension for joining strings with a ending delimiter.

    using System;
    using System.Windows.Forms;
    using ExtensionsLibrary;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                var startValue = 20;
                var endValue = 30;
                var testValue = 29;
                if (testValue.Between(startValue,endValue))
                {
                    Console.WriteLine($"{testValue} is between {startValue} and {endValue}");
                }
                else
                {
                    Console.WriteLine($"{testValue} is not between {startValue} and {endValue}");
                }
    
    
                var startDate = new DateTime(2018, 12, 2, 1, 12, 0);
                var endDate = new DateTime(2018, 12, 15, 1, 12, 0);
                var theDate = new DateTime(2018, 12, 13, 1, 12, 0);
    
                if (theDate.Between(startDate,endDate))
                {
                    Console.WriteLine($"{theDate} is between {startDate} and {endDate}");
                }
                else
                {
                    Console.WriteLine($"{theDate} is not between {startDate} and {endDate}");
                }
    
                string[] fruits = { "Apples","Cherries", "Grapes"};
                Console.WriteLine(fruits.JoinWithLastSeparator());
    
            }
        }
    }

    Results

    29 is between 20 and 30
    12/13/2018 1:12:00 AM is between 12/2/2018 1:12:00 AM and 12/15/2018 1:12:00 AM
    Apples, Cherries and Grapes

    In a forms project a developer constantly needs to get a specific type of control on a form were the specific type of control may be in various nested containers.

    /// <summary>
    /// Get a collection of a specific type of control from a control or form.
    /// </summary>
    /// <typeparam name="T">Type of control</typeparam>
    /// <param name="control">Control to traverse</param>
    /// <returns>IEnumerable of T</returns>
    public static IEnumerable<T> Descendants<T>(this Control control) where T : class
    {
        foreach (Control child in control.Controls)
        {
            T thisControl = child as T;
            if (thisControl != null)
            {
                yield return (T)thisControl;
            }
    
            if (child.HasChildren)
            {
                foreach (T descendant in Descendants<T>(child))
                {
                    yield return descendant;
                }
            }
        }
    }
    /// <summary>
    /// Get a collection of TextBox controls within a control.
    /// </summary>
    /// <param name="sender">Control to traverse</param>
    /// <returns>List of TextBox</returns>
    public static List<TextBox> DescendantsOfTextBoxes(this Control sender)
    {
        return sender.Descendants<TextBox>().ToList();
    }
    /// <summary>
    /// Get a collection of TextBox controls within a control.
    /// </summary>
    /// <param name="sender">Control to traverse</param>
    /// <returns>List of TextBox</returns>
    public static List<Button> DescendantsOfButtons(this Control sender)
    {
        return sender.Descendants<Button>().ToList();
    }

    We want all button controls in a groupbox, panel, panel.

    MessageBox.Show(descendantsGroupBox.DescendantsOfButtons()
        .Select(button => button.Text).ToArray().ToDelimitedString("\n"));

    A common practice is to place extension methods into a class project that then can be used in one or more Visual Studio solutions.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Tuesday, February 5, 2019 11:50 AM
    Moderator
  • We use it to add many methods to System.String, such as:

    	public static string StripWhiteSpace(this string expression)
    	{
    		return expression.Trim().Replace(" ", "");
    	}

    Then it can be called as if it were a regular string method:

    string strippedString = someString.StripWhiteSpace();



    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter



    Tuesday, February 5, 2019 3:56 PM