Reputation: 215
I have 4 methods which have similar code
private void LogExceptions(ObjA.Input input, int customerId)
{
//ObjA is a big object, thats why I try not to send the whole object in this method
Log(input);
Log(ObjA.Exceptions);
}
private void LogExceptions(ObjB.Input input, int customerId)
{
//ObjB is a big object, thats why I try not to send the whole object in this method
Log(input);
Log(ObjB.Exceptions);
}
and so on
I am not able to make it a template method such as
private void LogExceptions<T1,T2>(T1 input, int customerId) whereas T1:ObjA.Input,ObjB.Input
{
Log(T1);
Log(T2);
}
How to do it or is there any other way ? Any help is appreciated in advance .
I don't think my question was helping get proper answers.... Here is the exact code....
private void LogExceptions(AccARef.Response response)
{
StringBuilder sbErrors = null;
if (response.ValMethod != null && response.ValMethod.IsValid == false)
{
if (response.ValMethod.Errors.Count() > 0)
{
sbErrors = new StringBuilder();
foreach (AccARef.Exception exp in response.ValMethod.Errors)
{
sbErrors.Append(" * " + exp.Message + exp.StackTrace + " ");
Console.WriteLine(strError.ToString())
}
}
}
}
private void LogExceptions(AccBRef.Response response)
{
StringBuilder sbErrors = null;
if (response.ValMethod != null && response.ValMethod.IsValid == false)
{
if (response.ValMethod.Errors.Count() > 0)
{
sbErrors = new StringBuilder();
foreach (AccBRef.Exception exp in response.ValMethod.Errors)
{
sbErrors.Append(" * " + exp.Message + exp.StackTrace + " ");
Console.WriteLine(strError.ToString())
}
}
}
}
Now AcctBRef and AcctARef cannot implement a common interface as they are not my objects. Or if they are no my objects, can I still decorate them to be mine ?
Upvotes: 4
Views: 153
Reputation: 8913
What I feel is if there are 4 methods and they don't have same method signature its completely fine, it doesn't always have to be generic it has to be readable as well.
Why would you make 4 calls Log(T1),Log(T2),Log(T3),Log(T4)
if all you have to do is Log(OneofTheTypeWhichYouKnowWhenCallingTheMethod)
.
Having said that you can always have reflection to play around like in your case.
Upvotes: 0
Reputation: 29
You cannot pass Type parameter to Log method. You have to pass an instance of Type parameter.
try following:
private void LogExceptions<T1, T2>(T1 input, T2 exceptions, int customerId)
{
Log(input);
Log(exceptions);
}
Upvotes: 0
Reputation: 11782
You don't even need generics in this case, if ObjA and ObjB either inherit from the same base blass or interface.
If you have
interface IBaseClass
{
IEnumerable<Something> Exceptions {get;set;}
InputType Input {get;set;}
}
class A : IBaseClass {}
class B : IBaseClass {}
You can just use this for your LogExceptions signature:
void LogExceptions(IBaseClass obj, int CustomerId)
{
Log(obj.Exceptions);
Log(obj.Input);
}
If they don't inherit from a common interface, then I suggest they should.
Upvotes: 2