Loading [Contrib]/a11y/accessibility-menu.js
Back
Close

C# LINQ Background Topics

player_one
28.3K views

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
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.
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