Search code examples
c#jsongenericsdeserialization

How to use C# Generic with Constraint when Deserializing json payload


My generic definition:

public class OrderItemDrugTable<TRow> : TableBase where TRow : RowBase
{
    public List<TRow> rows { get; set; }
}

Class definition:

public class GenericCouch<TRow, TTable> where TRow : RowBase where TTable : TableBase

I am trying to deserialize json payload in my class:

var table = JsonSerializer.Deserialize<TTable>(result, options);

With this setup my variable "table" cannot access "rows" property available OrderItemDrugTable. I am trying to access "rows" in my GenericCouch class.

I am not able to deserialize like this (notice the TRow inside of TTable). It says "this type paramater TTable cannot be used with type arguments". Not sure if this is the way to do it or what the message means.

var table = JsonSerializer.Deserialize<TTable<TRow>>(result, options);

Solution

  • Without seeing the whole picture it is hard to advise, one approach you can try is introducing generic TableBase:

    public class TableBase<TRow> : TableBase where TRow : RowBase
    {
        public List<TRow> rows { get; set; }
    }
    
    public class OrderItemDrugTable<TRow> : TableBase<TRow> where TRow : RowBase
    {
    
    }
    
    public class GenericCouch<TRow, TTable> where TRow : RowBase where TTable : TableBase<TRow>
    {
        public void Do()
        {
            var table = JsonSerializer.Deserialize<TTable>(...);
            var tableRows = table.Rows;
        }
    }