Extension method

Extension methods add new functions to existing types.

Sometime it can be system types. For example, you can add extension method to string type.

Extension methods must stay in static class and must be static method itself.

The first parameter is marked by this keyword.


using System;

public static class StringHelper
{
    public static bool IsCapitalized(this string s)
    {
        if (string.IsNullOrEmpty(s)) return false;
        return char.IsUpper(s[0]);
    }
}
class Test
{
    static void Main()
    {
        string str = "java2s.com";
        Console.WriteLine(str.IsCapitalized());

    }
}

The output:


False
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.