2017년 2월 16일 목요일

[C#] Extension method

You can add new method into exist class using extension method.

Extension method is defined with static class, static method and this before first parameter.

Here is some simple example that to add new method to string class and int variable.


void Main()
{
Console.WriteLine("Father".IsCaptilized());
 Console.WriteLine(3.Duplicate());
}

public static class StringHelper
{
public static bool IsCaptilized(this string s)
{
if(string.IsNullOrEmpty(s))
return false;
return char.IsUpper(s[0]);
}
}

public static class IntHelper
{
public static int Duplicate(this int n) => n * 2;
}

StringHelper and IntHelper above classes are extension method for string and int.

댓글 없음:

댓글 쓰기