Wednesday, May 06, 2009

 

C# Code Snippet: Strip All HTML Tags

A quick code snippet to strip all HTML tags using a regular expression. If you are going to call something like this often, then it might be an idea to set the RegEx.Options to Compiled.

using System.Text.RegularExpressions;

...

public string StripHTMLTags(string text)

{

return Regex.Replace(text, @"<(?:.\n)*?>", string.Empty);

}

Note: I'm not suggesting using this for a full blown HTML-Sanitiser. See Jeff Atwood's post and the subsequent comments. (Thanks Piers!)

Labels: , , , , ,


Sunday, January 07, 2007

 

.Net C# Singleton Pattern - Best Practice

What is the best practice way to implement the Singleton design pattern in C#? You might be surprised at the number of flawed examples there are out there; many of the articles I looked at were incorrect (some subtlely, some not so) and several were on high traffic, popular sites!

This excellent article by Jon Skeet not only discusses several ways not to do it, but also the correct way:

public sealed class Singleton

{

// Prevent compiler adding a default public parameterless constructor

private Singleton() {}

public static readonly Singleton Instance = new Singleton();

// Explicit static constructor instructs compiler

// NOT to mark type as ‘beforefieldinit’

// Remove this if you do not need to guarantee lazy instantiation

static Singleton() {}

}


The static constructor is only required if you want to guarantee lazy instantiation (which Jon explains here.)

See also this MSDN article from Feb 2002.

Labels: , ,


    

Powered by Blogger