Add a Method to a Type Without Modifying It - CSharp Custom Type

CSharp examples for Custom Type:Extension Methods

Description

Add a Method to a Type Without Modifying It

Demo Code


using System;//from  w  ww .j a  v a 2 s  . c o m
using System.Collections.Generic;
using System.Linq;
using System.Text;

    public static class MyStringExtentions
    {
        public static string toMixedCase(this String str)
        {
            StringBuilder builder = new StringBuilder(str.Length);
            for (int i = 0; i < str.Length; i += 2)
            {
                builder.Append(str.ToLower()[i]);
                builder.Append(str.ToUpper()[i + 1]);
            }
            return builder.ToString();
        }

        public static int countVowels(this String str)
        {
            char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
            int vowelcount = 0;
            foreach (char c in str)
            {
                if (vowels.Contains(c))
                {
                    vowelcount++;
                }
            }
            return vowelcount;
        }
    }


class MainClass
    {
        static void Main(string[] args)
        {
            string str = "The quick brown fox jumped over the...";
            Console.WriteLine(str.toMixedCase());
            Console.WriteLine("There are {0} vowels", str.countVowels());
        }
    }

Result


Related Tutorials