Why extension methods for Blazor's ComponentBase class are only available trough this?

Viewed 369

I needed to extend all the Blazor components with a couple of convenient methods (doesn't matter why, just some project-specific stuff).

I'm not sure if it is the only way to do it in Blazor, but I decided to use the good old extension methods:

public static class ComponentBaseExtensions
{
    public static string MyMethod(this ComponentBase component, ...)
    {
        ...
    }
}

Everything went fine, except one annoying issue: these extension methods are only awailable if I call them through this, i.e. that code is valid:

<div class="@this.MyMethod()"></div>

and this one isn't:

<div class="@MyMethod()"></div>

So, the question is: why it behaves like that and how to get rid of it (if possible) to make the razor templates cleaner?

2 Answers

I needed to extend all the Blazor components with a couple of convenient methods

Then you could use inheritance. Add a base class

 class MyComponentBase : ComponentBase 
 { 
   protected string MyMethod(int x) { }
 }

and on top of all relevant pages:

 @inherits MyComponentBase

    ... MyMethod(7);

Got it now: it's actually absolutely normal C# behavior, looks like I just wanted it to work in a special way in context of razor templates. So, the question is a bit stupid, but maybe it'll help to someone who will be confused the same way as me :-)

Related