Evil Code #010 : Extension Methods

Back with Evil Code Series again. What would be the output of the following.

void Main()
{
PrintToString("SampleText");
PrintToDescription("SampleText");
PrintToString(null);
PrintToDescription(null);
}
public void PrintToString(string valueToPrint)
{
Console.WriteLine($"Printing From {nameof(PrintToString)} : {valueToPrint.ToString()}");
}

public void PrintToDescription(string valueToPrint)
{
Console.WriteLine($"Printing From {nameof(PrintToDescription)} : {valueToPrint.ToDescription()}");
}

public static class Extensions
{
public static string ToDescription(this string source)
{
return $"Description = {source??"Null"}";
}
}

The code attempts to prints 2 set of data, “SampleText” and Null Value. The PrintToString method, prints the output from the inbuild ToString() method, while the second method PrintToDescription, prints the output from an extension method.

The extension method, as such, doesn’t do anything fancy. It merely adds a prefix to the string (if not null or prints null).

It would be natural to expect the firs two method calls to print normally and then the last two calls, with null as paramter, to throw exceptions. But this is where things to change and expose the functioning of Extension methods.

While the extension methods work quite similiar to instance method, there is one fundamental difference. It has ability to execute even if the source instance if null.

In our given code, in the final call to PrintToDescription, even with a null paramter, the extension method is invoked, while the PrintToString would throw an exception as soon as null.ToString is encountered.

The output of the above code would be as following.

1. Printing From PrintToString : SampleText
2. Printing From PrintToDescription : Description = SampleText
3. // Throws Exception
4. Printing From PrintToDescription : Description = Null
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s