Typed APIs in 2sxc 16+
Typed Mode is a new way to write C# and Razor code in 2sxc 16+. It is much more robust and easier to debug than the classic dynamic code.
What does Typed Mode Look Like?
@inherits Custom.Hybrid.RazorTyped
<h1>@MyItem.String("Title")</h1>
@MyItem.Picture("Screenshot", imgClass: "float-right")
<ul>
<li>Teaser: @MyItem.String("Teaser")</li>
<li>Launched: @MyItem.DateTime("Launched").Year</li>
<li>Authors: @MyItem.Children("Authors").Count()</li>
<li>Maker: @MyItem.Child("Maker").String("Name")</li>
</ul>
@MyItem.Html("Description")
What's great about this is that every value is strong-typed, so VS-Code can give you IntelliSense, and the compiler will catch many more issues.
Important
Older code is dynamic. The API is quite different, so if you copy old snippets you'll probably need to refactor it.
Major Differences
- The compiler can detect many more issues in typed mode
- If your code isn't correct, you will get much better errors in typed mode
- Accessing invalid properties will throw an error in typed mode (eg.
MyItem.String("InvalidProperty")
will throw, butContent.InvalidProperty
will not) - Typed code works much better with LINQ, so
MyItem.Children("Authors").Count()
will just work (in dynamic mode you'd need to cast it toIEnumerable<dynamic>
first)
Activate Typed Mode
Dynamic and Typed code can coexist in the same app. Each Razor / C# file can decide which mode it wants to use. To be in typed mode, your Razor/C# must inherit from a typed base class like this:
- Razor files should begin with:
@inherits Custom.Hybrid.RazorTyped
- C# files should have something like:
public class YourClassName : Custom.Hybrid.CodeTyped
- WebApi files should be like:
public class YourControllerName : Custom.Hybrid.ApiTyped
Tip
Changing the base class will completely change the APIs you have available.
Configure Visual Studio Code for IntelliSense
Now that everything is typed, we highly recommend you setup VSCode to provide IntelliSense.
👉 Check out the VS Code Setup Docs