ElMatador
ElMatador

Reputation: 586

How to instantiate, operate and return Type T

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?)

Upvotes: 4

Views: 161

Answers (2)

Mark Byers
Mark Byers

Reputation: 838806

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);

Upvotes: 14

Jon Senchyna
Jon Senchyna

Reputation: 8047

Right now, your program just knows that T is at least an object that has a parameter-less constructor. You need to update your where T to include an interface constraint that tells your function that T is a member of some interface that contains a definition for CreditorName, CreditLiabilityID, and BorrowerID. You could do this like so:

where T: InterfaceName, new()

Upvotes: 9

Related Questions