Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate, operate and return Type T

Tags:

c#

generics

I have a function that I would like to return a CreditSupplementTradeline or a CreditTradeline using generics. The problem is that if I create a T ctl = new T(); ... I can not operate on ctl because VS2010 does not recognize any of its properties. Can this be done? Thank you.

    internal T GetCreditTradeLine<T>(XElement liability, string creditReportID) where T: new()
    {
        T ctl = new T();
        ctl.CreditorName = this.GetAttributeValue(liability.Element("_CREDITOR"), "_Name");
        ctl.CreditLiabilityID = this.GetAttributeValue(liability, "CreditLiabilityID");
        ctl.BorrowerID = this.GetAttributeValue(liability, "BorrowerID");
        return ctl;
    }

I get this error:

Error 8 'T' does not contain a definition for 'CreditorName' and no extension method 'CreditorName' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

like image 901
ElMatador Avatar asked Nov 28 '22 16:11

ElMatador


1 Answers

You need to have an interface with the appropriate properties, for example something like this:

internal interface ICreditTradeline
{
     string CreditorName { get; set; }
     string CreditLiabilityID { get; set; }
     string BorrowerID { get; set; }
}

On your method you need to add a constraint to T requiring that it must implement the above interface:

where T: ICreditTradeline, new()

Your two classes should implement the interface:

class CreditTradeline  : ICreditTradeline
{
     // etc...
}

class CreditSupplementTradeline  : ICreditTradeline
{
     // etc...
}

Then you can call the method with the class as your type parameter:

CreditTradeline result = this.GetCreditTradeLine<CreditTradeline>(xElement, s);
like image 50
Mark Byers Avatar answered Dec 01 '22 07:12

Mark Byers