✅ Extension Methods

this is an extension method that i have read in the docs , my question is when i use this extension method as below code in that case the this keyword bind the sentence string inside method as i did not pass any parameter correct?
c#
namespace StringExtnsion
{
public static class WordCountExtinsion
{
//this is used to bind the method to the main class
public static int WordCount(this String str)
{
string[] strings = str.Split(new char[] { ' ' , '?' });

return strings.Length;
}
}
}
c#
namespace StringExtnsion
{
public static class WordCountExtinsion
{
//this is used to bind the method to the main class
public static int WordCount(this String str)
{
string[] strings = str.Split(new char[] { ' ' , '?' });

return strings.Length;
}
}
}
c#
string? sentence = "My Name Is Mina?mina";

Console.WriteLine(sentence.WordCount());
c#
string? sentence = "My Name Is Mina?mina";

Console.WriteLine(sentence.WordCount());
5 Replies
Servator
Servator4mo ago
"Hello World!".WordCount()
"Hello World!".WordCount()
Yes it's correct.
blueberriesiftheywerecats
Basically it compiles to
WordCountExtension.WordCount("whatever")
WordCountExtension.WordCount("whatever")
steven preadly
steven preadlyOP4mo ago
i mean this in that case is the sentence correct
Jimmacle
Jimmacle4mo ago
yes, the this argument in an extension method is the object that you called the extension method on you did not pass it yourself, but like blueberries explained the compiler does some shuffling behind the scenes to pass it for you
steven preadly
steven preadlyOP4mo ago
ok thank you all
Want results from more Discord servers?
Add your server