C# – Use HttpUtility.HtmlEncode or create extension method

cnet

Should I use HttpUtility.HtmlEncode or write an extension method?

Pro for using HttpUtility.HtmlEncode is that other developers can instantly see and recognise what it's doing.

Pro for using an extension method is that it's less code to write everywhere and less noise.

So I guess I'm asking obvious readability vs tidier code.

Best Answer

Assuming you will call HttpUtility.HtmlEncoded() from your extension method (otherwise it's a no-no) and also that you will use a meaningful name to your method (otherwise you will just make code less clear). Given:

string someText = "This is some text";

Let's compare:

string htmlEncoded1 = someText.ToHtmlEncodedString();
string htmlEncoded2 = HttpUtility.HtmlEncode(someText);

Honestly I do not see any big improvement. Now let's introduce C# 6 static using feature:

string htmlEncoded1 = someText.ToHtmlEncodedString();
string htmlEncoded2 = HtmlEncode(someText);

I think it's clear which one is better. Also note that HttpUtility.HtmlEncode() has three overloaded methods and I usually consider a very bad practice to pollute object with useless extension methods.

Note that "...less code to write..." is not always and undoubtedly better. String conversions are an important and critical (both for performance and for security). If you name your method ToHtmlString() but - with help of Intellisense - you write ToString() you may have a potentially big bug latent in your code which may go unnoticed in a code review session.

Related Topic