Hello friends. In this article, I will talk about how to write an extension in C #. First, let’s talk about what is an extension. Extension actually means an extension in Turkish. In fact, if we look at it, it fits our definition. Because Extenison is actually giving an extra feature to a class or an object. You can think of it as adding a function. In the example we will do today, we will add a function to the String class and print our name. This class doesn’t need to be a String. We can also write Extension to the classes we have created.
In the example I will do in this article, I will add a function that I print my name to a string class. I’m creating a class for this. This class needs to be static. The function we will write must be static. Another thing we need to pay attention to is that this class and function is public. As the last operation, we will add this as the parameter of our function. However, we indicate that this function is an extension.
using System; namespace CurrencyMVVM.Extensions { public static class StringExtensions { public static string WriteName(this string str) { return "Omer Sezer"; } } }
It is necessary to use this function as the last operation. For this, we need to add the class with extensions to the namespace area to see the function we have created in any of your string objects. After that, you can use it comfortably.
If you have questions, you can reach by e-mail or comment. Good work.
Leave a Reply