For a long time a small thing in writing Razor code for Sitecore (and in some other places) has irritated me. It's not really very important, but with the new version of C# there is finally a way to round off this rough edge that's been getting to me...

What was the issue? Copy link icon url copied!

There are various places in the .Net world where Microsoft built a thing and we get to extend it. One of these places is in ASP.Net's Html object, which exposes a bunch of useful helpers for web programming. But in quite a few places (like Sitecore renderings) products and tools have added extra features this using Extension Methods. For example, displaying a Sitecore field in a rendering can look like:

<h1>
  @Html.Sitecore().Field("Title")
</h1>

					

And here's the thing that's irritated me: When you write an add-on like Sitecore() here, in the past this had to be a method - and hence the need for () on the end of the name.

That's because until now, the compiler only supported methods that acted as extensions to a someone else's object. So you'd declare that Sitecore extension something like:

public static SitecoreExtensions
{
   public static SitecoreExtensionClass Sitecore(this IHtmlHelper helper)
   {
      // return your custom helper object
   }
}

					

And the compiler understands it can extend ASP.Net's Html helper object to return the custom Sitecore code for you. It can re-write the code behind the scenes so that your method gets called passing in the HTML Helper object that Microsoft provide.

But the need to make the extension here a method rather than a property has always looked a bit wrong in my mind.

How can we do that better? Copy link icon url copied!

But the new v14 release for C# (Available with previews of .Net 10) has a new and more flexible way to declare extensions. You can still declare extension methods, but also now you can write extension properties.

The syntax is a bit different because there's no natural way to pass the equivalent of the this parameter into a property, but in future it will be possible to declare helpers like the Razor add-on above more like this:

public static SitecoreExtensions
{
    extension(IHtmlHelper helper)
    {
        public SitecoreExtensionClass Sitecore
        {
            get
            {
                // return your custom helper object
            }
        }
    }
}

					

And now because it's declared as an extension property there's no need for that extra () and your Razor code can become:

<h1>
  @Html.Sitecore.Field("Title")
</h1>

					

To me at least, that looks better.

Shame it won't work on your old DXP code - but maybe the .Net headless codebase might adopt it in future?

↑ Back to top

C# is fixing a thing that irritated me!