Answers for "c# extension method"

C#
4

define extension methods c#

public static class MyExtensions
{
  //use the this keyword before an argument
  public static int WordCount(this String str)
  {
    return str.Split(new char[] { ' ', '.', '?' },
                     StringSplitOptions.RemoveEmptyEntries).Length;
  }
}
Posted by: Guest on July-25-2020
0

c# add method to type

using System.Linq;
using System.Text;
using System;

namespace CustomExtensions
{
    // Extension methods must be defined in a static class.
    public static class StringExtension
    {
        // This is the extension method.
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined.
        public static int WordCount(this String str)
        {
            return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}

namespace Extension_Methods_Simple
{
    // Import the extension method namespace.
    using CustomExtensions;
  
    class Program
    {
        static void Main(string[] args)
        {
            string s = "The quick brown fox jumped over the lazy dog.";
            // Call the method as if it were an
            // instance method on the type. Note that the first
            // parameter is not specified by the calling code.
            int i = s.WordCount();
            System.Console.WriteLine("Word count of s is {0}", i);
        }
    }
}
Posted by: Guest on September-16-2020
0

c# extension

public static class MyClassExtension
{
  // This is the method you are adding to a class "MyClass"
  public static string GetValue(this MyClass myClass)
  {
    return value.toString();
  }
}

// This is how you can use it in other parts of your code
MyClass myClass = new MyClass();
string s = myClass.GetValue();
Posted by: Guest on August-23-2020
0

c# extension method

class ExtensionMethods2
{

    static void Main()
    {
        int[] ints = { 10, 45, 15, 39, 21, 26 };
        var result = ints.OrderBy(g => g);
        foreach (var i in result)
        {
            System.Console.Write(i + " ");
        }
    }
}
//Output: 10 15 21 26 39 45
Posted by: Guest on July-14-2021

C# Answers by Framework

Browse Popular Code Answers by Language