I am reading a post about mobile web development and ASP.NET MVC here: http://www.hanselman.com/blog/ABetterASPNETMVCMobileDeviceCapabilitiesViewEngine.aspx.
In the article, Scott Hanselman goes through the process of creating his own view engine to render different views based on whether the site is requested from a mobile web browser or not.
In his MobileHelpers class, he has several methods with signatures that are very foreign to me. Here’s an example:
public static void AddMobile<T>(this ViewEngineCollection ves, Func<ControllerContext, bool> isTheRightDevice, string pathToSearch)
where T : IViewEngine, new()
{
ves.Add(new CustomMobileViewEngine(isTheRightDevice, pathToSearch, new T()));
}
I’ve worked a little bit with inline functions like this (I think thats what they’re called) but this logic is eluding me. I don’t understand the purpose of the where T : ...... line either.
Could you guys help me understand what is happening here?
It would help if you could identify which parts in particular are confusing to you. I’ve picked the two I think are the most likely based on your question, and explained those. If there is any other syntax that is confusing you, please edit your question to explain which.
Explanation for
where T : IViewEngine, new()C# allows you to place constraints on generic type parameters. You can read more about constraints here.
In your particular case,
where T : IViewEnginemeans that whatever typeTis must be a descendant of theIViewEnginetype.where T : new()is special syntax that indicates that whatever typeTis must have a default constructor.Explanation for
this ViewEngineCollection vesThe keyword
thismeans that the methodAddMobileis an extension method to theViewEngineCollectionclass. This means that in addition to being called asAddMobile(someViewEngineCollection, ...), it can be called assomeViewEngineCollection.AddMobile(...). You can read more about extension methods here.