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:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With