var in c# to support either Type1 or Type2

Viewed 66

I have two auto-generated classes, say Type1 and Type2. Each of these classes deals with other related auto-generated classes. Since they are auto-generated, I cannot change them to use either abstract classes or interfaces. I have two methods, one return Type1 and the other return Type2. Type1 and Type2 are almost the same, so I wanted to call them like below to avoid code duplication on my side, of course it did not work as the type needs to be known in compile time.

var response = string.IsNullOrWhiteSpace(inputObject.HistoricYear) ? Type1: Type2;
if (string.IsNullOrWhiteSpace(inputObject.HistoricYear))
{
    response = TsiService.GetAccountTransactionsList(inputObject);
} else
{
    response = TsiService.GetAccountTransactionsHist(inputObject);
}

I also tried using object and then I get this error object does not contain a definition for MEMBER_1 and MEMBER_2, etc.:

var response = null;
if (string.IsNullOrWhiteSpace(inputObject.HistoricYear))
{
    response = TsiService.GetAccountTransactionsList(inputObject);
} else
{
    response = TsiService.GetAccountTransactionsHist(inputObject);
}

CustomObject.member1 = response.MEMBER_1;
CustomObject.member2 = response.MEMBER_2;

Any idea how to do it?

1 Answers

The canonical solution would be to make sure that both Type1 and Type2 implement a common interface defining MEMBER_1, MEMBER_2, etc.

Since you cannot do that for technical reasons, you have two options:

  1. Create wrapper types: Create a new class Type1WithInterface, which has the same members as Type1, but also implements that common interface described above. Type1WithInterfaces gets a Type1 instance in its constructor and passes every property access to the underlying Type1.

  2. Alternatively, you can use the dynamic keyword. It disables compile-time type checks for member accesses.

The drawback of option 1 is that you will have to write a lot of boiler-plate code, but the advantage is that you will retain type safety. With option 2, all type safety bets are off, and typos will bite you at run-time rather than at compile-time.

Related