C# LINQ Background Topics
player_one
127.5K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Extension Methods - Extra parameters
An extension method can take extra parameters, in addition to an instance of the type that it is extending. Here is an example of how this works:
namespace IntExtensions
{
public static class CoolExtensionsForInt
{
public static string Growl(this int num, char a, char b)
{
return $"{a}{new string(b, num)}";
}
}
}
What does this do? Let's call it a few times and find out:
using IntExtensions;
...
// Prints "Grrrrrrr" to the console
Console.WriteLine(7.Growl('G', 'r'));
// Prints "Brrr" to the console
Console.WriteLine(3.Growl('B', 'r'));
// Prints "Shhhh" to the console
Console.WriteLine(4.Growl('S', 'h'));
Exercise
Try adding another extension method to the string
type. This time, call it MakePlural()
. The MakePlural()
method should take an int
parameter and return a string that is either the original string if the parameter is 1, or the string with an 's' appended to it if the parameter is not equal to 1.
Extension Method Parameters Exercise
1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace ExtensionMethods2
{
// Write the extension method (and containing class) here,
// following the example in the lesson. The method should
// be called MakePlural(), extends string, takes an int
// parameter, and returns a string.
//
// If the passed-in int is 1, then MakePlural() should
// return the original string, unmodified. Otherwise, it
// should return the string with an 's' appended to it.
// public ... class ...
// { }
}
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content