Reputation: 1020
I have a generic method which returns a type T. Now I want to modify it so that if T happens to implement interface I, an additional property is set on the object (i.e. from I).
Something like this (but of course this does not work):
public T MyMethod<T>()
{
T resultAsT = some function ....
var resultAsI = (resultAsT as I);
if (resultAsI != null)
{
resultAsI.PropertyOnlyAvailableInI = 99;
return resultAsI;
}
else
return resultAsT;
}
Is something like this possible?
Upvotes: 0
Views: 179
Reputation: 9
If you really want to make it work then you can do so:
public object MyMethod()
{
object resultAsT = something;
var resultAsI = (resultAsT as ISomething);
if (resultAsI != null)
{
resultAsI.PropertyOnlyAvailableInI = 99;
return resultAsI;
}
else
return resultAsT;
}
But it seems to me that you want to do factory that implements the strategy pattern. Where the object is created with the use of strategy pattern is executed to initialize certain properties of the object.
Upvotes: -1
Reputation: 14059
This should work:
public T MyMethod<T>()
{
T resultAsT = some function ....
var resultAsI = (resultAsT as I);
if (resultAsI != null)
{
resultAsI.PropertyOnlyAvailableInI = 99;
}
return resultAsT;
}
The method cannot return anything except T
, so you should always return resultAsT
.
Upvotes: 7