Tuesday, November 25, 2008

Create a CssStyleCollection instance programmatically

Update 2011-07-12: Refer to this answer on Stackoverflow for a more elegant solution.

The CssStyleCollection class is a very useful class in ASP.NET. It manages CSS nicely in a programmatic way. However, if you would like to create an instance of this class in your own code, you will find it rather impossible. The class is sealed, so there is no way to inherit it. Moreover, the constructors are private, so you cannot create a new object!

I've seen many questions about how to create an instance of this class in online forums when I searched for it myself today. The solution is to delve into the internals of the class with Reflection. In that way it is possible to call the two private constructors of the class.

You can use the code below:

using System.Reflection;
using System.Web.UI;

namespace Tools
{
public class CssStyleTools
{
/// <summary>
/// Creates an instance of the CssStyleCollection class by reflection.
/// </summary>
/// <returns>A new instance of the CssStyleCollection class.</returns>
public static CssStyleCollection Create()
{
return (CssStyleCollection)typeof(CssStyleCollection).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0].Invoke(null);
}

/// <summary>
/// Creates an instance of the CssStyleCollection class by reflection and stores view state in the provided state bag.
/// </summary>
/// <param name="state">The storage object for the state.</param>
/// <returns>A new instance of the CssStyleCollection class.</returns>
public static CssStyleCollection Create(StateBag state)
{
return (CssStyleCollection)typeof(CssStyleCollection).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[1].Invoke( new object[]{ state });
}
}
}

It is as simple as calling the following code:

CssStyleCollection css = CssStyleTools.Create();

Feel free to comment if it was any use to you.

2 comments:

Amir said...

Hi!
I your code very helpful for a project I'm working on.
Thank you for sharing it.
But still I wonder, why isn't CssStyleCollection available normally? Why are its constructors private?

- Amir

Andres95 said...

man... you're really good, this stuff was driving me crazy...

Thanx a lot!...