How do you write an Extension Method? How do you refer to the "thing" your extension method is supposed to operate on?

I am just learning about Extension Methods in C#, and I don’t understand how I’m supposed to refer to the the thing the method operates on. It’s not really an “argument” provided to the method, so how do I write code to refer to it?

So for example, this one exercise I am working on wants me to write an Extension Method to the string class that takes a string delimiter as an argument. This method should then return everything after the delimiter. So if I get the string message “[Hello]: Dolly!”, and I provide the method with ": " as an argument, I expect it to return “Dolly!”. The problem is that I don’t know how to refer to the entire string message as anything but an argument.

1 Like

Just for context: I guess you’re trying to solve the log-analysis concept exercise, right?

Take another look at the introduction: Extension methods take a first parameter that is preceded by the keyword this, and you can operation on this parameter.

(Disclaimer: I wouldn’t call myself a C# programmer, I just want to help out until the real experts show up.)

1 Like

The string being acted on (i.e. the log record) is passed as a parameter using this <type> <name> and is referenced within the method using the name. You also need to add a parameter for the delimiter string.


public static string SubstringAfter(this string message, string delimiter)
    // your code

Hope that helps!