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.
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.)
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.
e.g.
public static string SubstringAfter(this string message, string delimiter)
{
// your code
}
Thanks this really helped to get me unstuck. The instructions weren’t clear about including a second string parameter representing the actual log message.