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?)
You need to have an interface with the appropriate properties, for example something like this:
On your method you need to add a constraint to
Trequiring that it must implement the above interface:Your two classes should implement the interface:
Then you can call the method with the class as your type parameter: