Home > Blockchain >  Generics for two classes: .NET 6
Generics for two classes: .NET 6

Time:09-20

I am trying to instantiate class with common fields using generics.

if (payload?.tableA?.name == "a")
{
    Report rpt = new Report ();
    ABC a = rpt.FillReport<ABC>(payload);
}
else
{
     Report rpt = new Report();
     BCD b = rpt.FillReport<BCD>(payload);
}

Now the field for ABC and BCD are as follows

class A{
   pageId, paperType, printType, Volume
}

class B{
  pageId, paperType, paperColor, Volume, Weight
}

So now How should I use generics here.This is what I tried.

public T FillReport<T>(DTO? dto) where T : ABC, new()
{
    T report = new T();
    report.pageId = dto.pageId;
    report.paperType= dto.paperType;
...
}
//Works for only ABC, how Do it BCD fields.

CodePudding user response:

Create an interface ISomething and make ABC/BCD both inherit from that same interface:

public interface ISomething 
{
    pageId {get;set;}
    pagerType {get;set;}
}

class A : ISomething
class B : ISomething

Then on your method declaration:

public T FillReport<T>(DTO? dto) where T : ISomething, new()
  • Related