Strong Types Explained - How to Use Runtime Typing

JanL@kentico.com[email protected] Czech RepublicMember, Administrator, Kentico Staff admin

In this short series of articles, we'll explain one of the greatest key enhancements in our Delivery .NET SDK: the strong types.

Contents:

How to Use Runtime Typing

The only thing you need to do is fetch items as bare objects via the type parameter being set to object:

var itemsOfVariousTypes = deliveryClient.GetItemsAsync<object>(new InFilter("system.type", "brewer", "coffee"));

The response would look like the following:

var itemsOfVariousTypes = new IEnumerable<object>
{
    new Brewer
    {
        ProductName = "AeroPress",
        …
        Manufacturer = "Aerobie"
    },
    new Coffee
    {
        ProductName = "Brazil Natural Barra Grande",
        …
        Farm = "Sitio Barra Grande"
    }
}

The developer, or an existing framework like MVC, is then free to work with the data in whatever way they want. They have all the type information included. It is up to them to decide whether and how to use it.

In MVC, all that's required is to define display templates for all types in the respective filesystem locations (like ~/Views/Shared/DisplayTemplates/[type name].cshtml). MVC will use the type information to pick the right template.

On the other hand, if some of the items in the collection have similar characteristics, the developer may wish to implement inheritance as mentioned in part 2. Like so:

foreach (var product in itemsOfVariousTypes.Cast<Product>())
{
    product.ProductProductName += " (discounted)";
}

Of course, both the original collection and the more general one can coexist side by side at the same time. They can be used at will.

Future Plans

We've already brought the strong types to life in our MVC sample app and our Boilerplate for ASP.NET Core MVC. But we strive to improve and broaden the strong type approach in the SDK even more.

For example, we would like the SDK to be able to accept strongly typed filtering values. This way, you would be able to filter e.g. for articles dated at some point in time by supplying a DateTime predicate (instead of string).

If you have any ideas about strong types, you're more than welcome to tell us via the comments below. Or you can try implementing it right away and submit a pull request to one of our repositories.

Wrapping Up

In this final part of the series, we've shown how to utilize runtime typing quickly in apps. We've also touched on what we're up to in the near future.

Together with the GitHub wiki, this series of articles should give you a good head start to use runtime typing and all the strong type infrastructure in your projects.

Also, stay tuned as we plan on writing a similar article on MVC display templates!

Tagged:
Sign In or Register to comment.