Implementing Extension Methods in Design pretrains dot net
Loading
Implementing Extension Methods in Design pretrains dot net
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Blocked AccountPosted May 14, 2025, 5:33 AM
Hi Kiran,
Extemsion methos is a language feature but they are often used to implement or support design patterns.
An extension method allows you to "add" new methods to existing types without modifying the original type or creating a new derived type.
In the above code I have just created extension method IsNullOrEmpty, that will retutn bool value true if string is null or empty. It is just one example. You can create as muach as you want.
Thanks
Blocked AccountPosted May 16, 2025, 6:45 AM
In the code above, I created two classes. In one class, I used the
thiskeyword in the method parameter, making it an extension method. In the other class,StringExtensionsWithoutThis, I didn’t usethis, so it’s just a regular static method.Now, if you look at the
Mainmethod, I declared a string variable. When I type the variable name followed by a dot (.), the extension method appears in the IntelliSense suggestions, but the static method does not. This is because extension methods can be invoked as if they were instance methods on the type they extend.However, both the extension method and the static method can still be called using the
ClassName.MethodNamesyntax. Since you called the same method in both cases, the output remains the same.Kiran KumarPosted May 16, 2025, 5:07 AM
Yes, now I can understand the usage of this, but without this mentioned, I didn't get anyway I don't want to get in detail without this as you said it's a rule to have a parameter this while implementing extension method, but my question is how the same logic works without using this and having a static method and invoke it with the class name can you please confirm
Blocked AccountPosted May 15, 2025, 4:53 AM
If you do not use the
thiskeyword in the first parameter of your method, it is not an extension method-it is just a regular static method. Thethiskeyword in the parameter is what tells the C# compiler to treat the method as an extension method for the specified type.Key differences:
With
this: You can call the method as if it were a member of thestringclass (i.e.,myString.IsNullOrEmpty()).Without
this: You must call the method as a static method on the class where it is defined (i.e.,StringExtensions.IsNullOrEmpty(myString))I hope now it's clear to you.
Kiran KumarPosted May 15, 2025, 3:14 AM
HI Dwivedi
Thanks for the information in this pattren do we need to use this keyword I can get the similar result even if dont use this keyeword in function signature can you please confirm
Kiran