How do i get a custom string extension in visual studo

I am trying to get this method into my project how do i do it http://extensionmethod.net/1718/csharp/string/leftof

1 answer

  • answered 2018-11-07 23:18 Levon Ravel

    Here is a extension example per your request. The extenstion is created via the Extensions class you can put many extensions in here. The way the extension is initially created is the first parameter would be the type you want to extend by using "this" modifier and then your Type. Any other parameters following can be utilized to perform your logic. From here any time you utilize the Type you can see the extension IE myString.LeftOf('somecharacter');

    using System;
    namespace YourNameSpace
    {
        class Program
        {
            static void Main(string[] args)
            {
                string myString = "Hello World";
                char character = 'l';
                string result = myString.LeftOf(character);
                Console.WriteLine(result);
            }       
        }
    
        public static class Extensions
        {
            public static string LeftOf(this string s, char c)
            {
                int ndx = s.IndexOf(c);
                if (ndx >= 0)
                {
                    return s.Substring(0, ndx);
                }
    
                return s;
            }
        }
    }