Search code examples
c#genericstype-constraints

What does this C# syntax do?


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?


Solution

  • 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 : IViewEngine means that whatever type T is must be a descendant of the IViewEngine type. where T : new() is special syntax that indicates that whatever type T is must have a default constructor.

    Explanation for this ViewEngineCollection ves

    The keyword this means that the method AddMobile is an extension method to the ViewEngineCollection class. This means that in addition to being called as AddMobile(someViewEngineCollection, ...), it can be called as someViewEngineCollection.AddMobile(...). You can read more about extension methods here.