No Free Time

Because my therapist says I need to let things out

Constrain a generic Class/Method to a particular type

Posted by andrewmyhre on April 2, 2008

In C# you can constrain a generic type using the where T:Type syntax. For instance, my method to get a Url for a particular CMSObjectType (my base CMS domain object class) I declare the method like this:

public string GetUrl<T>() where T:CMSDataObject

This instructs the compiler that it will only accept types passed into the generic method which derive from CMSDataObject. The syntax is also valid for generic classes.

More information at MSDN: http://msdn2.microsoft.com/en-us/library/bb384067.aspx

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>