Back
Close

Extension methods in C#

gpeipman
1,682 views

What is extension method?

Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.

Extension methods are static methods of static class and they use "this" keyword in argument list to specify the type they extend. The following demo shows how to build extension method that returns word count in string.

using System;
class Hello
{
static void Main()
{
var sentence = "one beer, please!";
Console.Write("Word count in sentence: ");
Console.WriteLine(sentence.WordCount());
}
}
public static class StringExtensions
{
public static int WordCount(this string s)
{
return s.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries)
.Length;
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants