Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generics for two classes: .NET 6

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading