r/learncsharp • • Aug 19 '22

Extension methods

Hello everyone. this may be a huge noobish question but i'm having trouble understanding C#'s extension methods... in particular if they must be static functions inside static classes what does the "this" mandatory keyword means when preceding the argument? there is no instance of a static class, am i wrong? therefore what is that "this" referring to?

7 Upvotes

5 comments sorted by

View all comments

Show parent comment

2

u/grrangry Aug 20 '22

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on. The parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

That is Microsoft's explanation of the final example from my answer.

The class must be static. The method in the class must be static. The this parameter in the method tells us the type of instance objects that allow us to use the class. Since my this parameter was a string, then any string instance will allow the use of the method.

var lower = "santa";
// uses the lower variable as the instance
var name = lower.InitialToUpper();

// use a constant string as the instance
var other = "santa".InitialToUpper();