Denis Jakus

Demystifying Tech & Management

CTO x Unique People

AI / ML / ChatGPT

Unreal Engine

Low Code

Management & Leadership

IT Consultant

Denis Jakus

Demystifying Tech & Management

CTO x Unique People

AI / ML / ChatGPT

Unreal Engine

Low Code

Management & Leadership

IT Consultant

CTO Note

Extension Methods2 min read

03 September 2017 .NET
Extension Methods2 min read

What are extension methods and how do you write them?

Let’s dive together into extension methods world and make our future code more productive and easier to read and maintain.

DEFINITION OF EXTENSION METHOD

Extension methods are nothing else but methods which we write to extend or add additional functionalities to an existing class and all of that without changing it’s source code or creating a new class which inherits from it.

They are static methods which MUST start with this  keyword as a first parameter, to know which type we are extending.

So let’s see how to write extension methods and how to use them!

EXTENSION METHOD IN ACTION

[syntax_prettify  linenums="linenums"]
static void Main(args) {
    string someText = "Some super duper cool text which needs to get shortened!";
    var shortenedText= someText.Shorten(3);
    Console.log(shortenedText);
    // output:  "Some super duper"
}
public static class ExtensionExamples {
    public static string Shorten(this string textToShorten, int numberOfWords){
        if (numberOfWords <= 0 ) {
            return "";
        }
        var words = textToShorten.Split(' ');
        if (words.Length <= numberOfWords) {
            return textToShorten
        }
        return textToShorten.Join(" ",textToShorten.Take(numberOfWords));
    }
}
[/syntax_prettify]

SUMMARY

  • They are custom methods which extend original functionalities
  • They can be added to any interfaces, struct or 3rd party classes
  • MUST be static type
  • Unlike static method, extension method MUST have this keyword as a first parameter to define a type which will be extended
  • They can be used inside application anywhere by including namespace of the extension method.

[UPDATED EXAMPLE AT 16.7.2019.]

How to display friendly names for enum in C#

If you have enum like this one:

[syntax_prettify linenums=”linenums”]
public enum DispatchDemandInputType
{
Default = 0,
[Description(“t/year”)]
TYEAR,
[Description(“m3/year”)]
M3DAY,
}
[/syntax_prettify]

And you want to access Description attribute easily in code (i.e. to output as a label text) like this:

[syntax_prettify linenums=”linenums”]
product.DemandType.GetDescription(); // where DemandType is of type DispatchDemandInputType (enum)
[/syntax_prettify]

Then all you have to do is write an extension method to make your life easier like this:

[syntax_prettify linenums=”linenums”]
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
return value.GetType().GetField(value.ToString())?.GetCustomAttribute()?.Description;
}
}
[/syntax_prettify]

Related Posts
Write a comment