Wednesday, July 26, 2023

Adding newer extension method(s) to struct types C#

 In this article, I will demonstrate on how one can add additional methods to existing struct types like int, string, char, long, etc,.

This can be beneficial when the existing methods for that type is like not handful for a certain situation say like reversing a string. Some of existing method say for string type includes `.ToUpper()`, `.ToLower()`, `.Trim()` and so on.

Let us call our new method Reverse().

First we need to have `static` class for it and `static` method like below.


```

public static class AfceClass

{

    public static string Reverse(this string theStr)
{

string theStrNew;

    foreach(char ch in theStr)
{

    thStrNew =+ ChangeCase(ch) ;

}

    return  thStrNew;


public static string ChangeCase(char chr)

{

    // steps to change or negate the char case
    return chr.toUpper();

}

}

```

Note, the use of the `this` keyword to the parameters which more or less makes the method chain.

Now, if you find any variables of type string, it should also have the Reverse() method as well and documentation if added in the comments for that method.

Extension method can be used of types other than struct or for user defined types as well. One aspect is the static class should not be nested in the same class where one is using it as well.

Sample using the generic type

```

public static class AfceClass

{

    public static E NewExtMethod<E, T>(this T theStr)
{

E theStrNew;

....

...

...

    return  thStrNew;

}

}

```
Now with Generics, the NewExtMethod<E, T> should populate with any types but make sure to pass the E and T types.

This can be further refined to be populated with only certain types with the `where` clause like below.

```

public static class AfceClass

{

    public static E NewExtMethod<E, T>(this T theStr) where T : long, int where E : long
{

E theStrNew;

....

...

...

    return  thStrNew;

}

}

```

Usage - One can use this to have like a common method say like add leading zeros to an int or a long and return as a string or even use as user types with much more options.

No comments:

Post a Comment

Browser background color or monitor brightness

Have you been in a situation where you are almost sitting the whole day in front of your browser and going through a document and find that ...