0

The code below was made using .Net 5.0.203

I've this component

MyComponent.razor

@typeparam TItem

<p>MyComponent: @typeName</p>

@code {
    [Parameter]
    public IEnumerable<TItem> Data { get; set; }

    string typeName;

    protected override void OnInitialized()
    {
        typeName = typeof(TItem).Name;
    }
}

and here is the page calling the component

Index.razor

@page "/"

<MyComponent Data="@items"></MyComponent>

<p>Page: @itemsType</p>

@code
{
    string[] items = new string[2];

    string itemsType;

    protected override void OnInitialized()
    {
        itemsType = items.GetType().Name;
    }
}

I expected the type of TItem in MyComponent is String[] however it's String

How Blazor infer the type of TItem?

vcRobe
  • 1,671
  • 3
  • 17
  • 35

1 Answers1

0

When you use the generic constraint of typeparam TItem is says when you create the component you must specify what that type is.

When you called your component here:

<MyComponent Data="@items"></MyComponent>

You passed the @items object as the parameter.

If you don't explicitly tell the component what type it should expect, it will by default use whatever type is passed to it.

You passed it a string[] so it said "He gave me a string[] so i'm going to assume the TItem is of type string". It does this because string[] is implicitly convertible to IEnumerable<TItem> since TItem can be any object unless you constrain that parameter. so it can only be certain types

Another thing of note is that TItem is the type of the object that is contained within the IEnumerable<TItem> parameter. If you want to check to see what type of IEnumerable that was passed instead maybe do something like:

string[] s = new string[] { "fox" };

Check(s);

static void Check<T>(IEnumerable<T> maybeArray)
{
    Console.WriteLine(typeof(T)); // System.String
    Console.WriteLine(maybeArray is T[]); // true
    Console.WriteLine(maybeArray is List<T>); // false
}

If you want TItem to be a string[] consider instead accepting TItem as a parameter instead of IEnumerable<TItem>.

Such as:

[Parameter]
public TItem Data { get; set; }

Make sure to include a constraint on TItem if you need it to be enumerable.

For more information on how to include a generic constraint in blazor (it's weird) check out this post)

DekuDesu
  • 2,224
  • 1
  • 5
  • 19