C# Extension Methods 2


This entry is part 2 of 2 in the series C# Extension Methods

Most of the time you will be using extension methods instead of creating them, as we did in the next post. What can we use them for? Mosh Hamedani gives us one example in the Extension Methods video at Udemy.com in the C# Advanced series of videos.

Here we can find the largest number in a list of numbers by using the extension method found in the LINQ namespace. Actually there are quite a few extension methods to be found in the LINQ namespace. The following modified example is from the book C# Pocket Reference Instant Help for C# 7.0 Programmers written by Joseph Albahari and Ben Albahari published by O’Reilly Media, Inc. copyright 2017.

using System;
namespace ExtensionMethods2
{
    public static class StringHelper
    {
        public static bool IsFirstLetterCapitalized(this string s)
        {
            if (string.IsNullOrEmpty(s)) return false;
            return char.IsUpper(s[0]); // IsUpper() returns bool
        } // string is an array of char
    }
    class Program
    {
        static void Main(string[] args)
        {
            var myString = "Hello";
            Console.WriteLine(myString.GetType()); // System.String
            Console.WriteLine(myString.IsFirstLetterCapitalized()); // True
            myString = "hello";
            Console.WriteLine(myString.IsFirstLetterCapitalized()); // Flase
        }
    }
}

Series Navigation<< C# Extension Methods