I have an interface:
public interface IPath
{
// Some method
}
and I have two classes which are inheriting this interface
public class First : IPath { }
public class Second: IPath { }
By the way, in some method I need to choose which class to use, First or Second, it depending on one string property (type), which I get from database. It looks like:
public void SomeMethod(string type)
{
if (type == "First") { // creating instance of First class }
else if (type == "Second") { // creating instance of Second class }
else { ... }
}
Question is: how can I avoid if/else or switch/case constructions and automaticly create the right instance, depending on the string variable?
You could create a dictionary to map from string to Type and the use that Type and Activator.CreateInstance to create an instance of that type.
Alternatively you could fetch the type using reflection and not need a dictionary at all
private Dictionary<string, Type> _iPathMapping = new Dictionary<string, Type>
{
{ nameof(First), typeof(First) },
{ nameof(Second), typeof(Second) },
};
// ...
public IPath Create(string path)
{
var type = _iPathMapping[path];
return (IPath) Activator.CreateInstance(type);
}
(You'd want to extend that code with safety checks, see below)
But this is fundamentally a bad solve. The problem to this is that it's harder to pass parameters to constructors and it's unsafe as well, if any of your implementations don't have a parameterless constructor, this will fail, but not with a compiler error, no it will fail during runtime, i.e once a user (or hopefully testers/ automatic tests) ran into the problem. So a better way would be to store a method that's invoked to construct the type instead of using Activator.CreateInstance, something like
private Dictionary<string, Func<IPath>> _iPathMapping = new Dictionary<string, Func<IPath>>
{
{ nameof(First), () => new First() },
{ nameof(Second), () => new Second() },
};
// ...
public IPath Create(string path)
{
if (_iPathMapping.TryGetValue(path, out var func))
return func.Invoke();
return null;
}
This solves the problem of parameters for the constructor in that it doesn't throw a runtime exception.
But we still haven't solved the problem of actually passing parameters to the constructor, especially when First and Second require different parameters. The only clean* way to I can think of to handle this in a generic and reusable way is using a Dependency Injection framework/ context to actually construct our instances.
But in general, the if/ else if chain or switch statement isn't necessarily a bad thing, you even see it in some places inside .NET
* You could replicate the part of a DI framework that's responsible for resolving dependencies for a constructor, but that's just re-implementing the wheel and might as well save the effort needed and just pull in a dependency like Microsoft.Extensions.DependencyInjection
I have a shorter version as answer, but I saw "MindSwipe" already offered you one:
Dictionary<string, Type> map = new Dictionary<string, Type>();
map.Add("First", typeof(First));
map.Add("Second", typeof(Second));
var instance = Activator.CreateInstance(map[<your parameter as string>]);
Related
I'm on a quest to write a TypedBinaryReader that would be able to read any type that BinaryReader normally supports, and a type that implements a specific interface. I have come really close, but I'm not quite there yet.
For the value types, I mapped the types to functors that call the appropriate functions.
For the reference types, as long as they inherit the interface I specified and can be constructed, the function below works.
However, I want to create an universal generic method call, ReadUniversal<T>() that would work for both value types and the above specified reference types.
This is attempt number one, it works, but It's not generic enought, I still have to cases.
public class TypedBinaryReader : BinaryReader {
private readonly Dictionary<Type, object> functorBindings;
public TypedBinaryReader(Stream input) : this(input, Encoding.UTF8, false) { }
public TypedBinaryReader(Stream input, Encoding encoding) : this(input, encoding, false) { }
public TypedBinaryReader(Stream input, Encoding encoding, bool leaveOpen) : base(input, encoding, leaveOpen) {
functorBindings = new Dictionary<Type, object>() {
{typeof(byte), new Func<byte>(ReadByte)},
{typeof(int), new Func<int>(ReadInt32)},
{typeof(short), new Func<short>(ReadInt16)},
{typeof(long), new Func<long>(ReadInt64)},
{typeof(sbyte), new Func<sbyte>(ReadSByte)},
{typeof(uint), new Func<uint>(ReadUInt32)},
{typeof(ushort), new Func<ushort>(ReadUInt16)},
{typeof(ulong), new Func<ulong>(ReadUInt64)},
{typeof(bool), new Func<bool>(ReadBoolean)},
{typeof(float), new Func<float>(ReadSingle)}
};
}
public T ReadValueType<T>() {
return ((Func<T>)functorBindings[typeof(T)])();
}
public T ReadReferenceType<T>() where T : MyReadableInterface, new() {
T item = new T();
item.Read(this);
return item;
}
public List<T> ReadMultipleValuesList<T, R>() {
dynamic size = ReadValueType<R>();
List<T> list = new List<T>(size);
for (dynamic i = 0; i < size; ++i) {
list.Add(ReadValueType<T>());
}
return list;
}
public List<T> ReadMultipleObjecsList<T, R>() where T : MyReadableInterface {
dynamic size = ReadValueType<R>();
List<T> list = new List<T>(size);
for (dynamic i = 0; i < size; ++i) {
list.Add(ReadReferenceType<T>());
}
return list;
}
}
An idea that I came up with, that I don't really like, is to write generic class that boxes in the value types, like this one:
public class Value<T> : MyReadableInterface {
private T value;
public Value(T value) {
this.value = value;
}
internal Value(TypedBinaryReader reader) {
Read(reader);
}
public T Get() {
return value;
}
public void Set(T value) {
if (!this.value.Equals(value)) {
this.value = value;
}
}
public override string ToString() {
return value.ToString();
}
public void Read(TypedBinaryReader reader) {
value = reader.ReadValueType<T>();
}
}
This way, I can use ReadReferencTypes<T>() even on value types, as long as I pass the type parameter as Value<int> instead of just int.
But this is still ugly since I again have to remember what I'm reading, just instead of having to remember function signature, I have to remember to box in the value types.
Ideal solution would be when I could add a following method to TypedBinaryReader class:
public T ReadUniversal<T>() {
if ((T).IsSubclassOf(typeof(MyReadableInterface)) {
return ReadReferenceType<T>();
} else if (functorBindings.ContainsKey(typeof(T)) {
return ReadValueType<T>();
} else {
throw new SomeException();
}
}
However, due to different constraints on the generic argument T, this won't work. Any ideas on how to make it work?
Ultimate goal is to read any type that BinaryReader normally can or any type that implements the interface, using only a single method.
If you need a method to handle reference types and a method to handle value types, that's a perfectly valid reason to have two methods.
What may help is to view this from the perspective of code that will call the methods in this class. From their perspective, do they benefit if they can call just one method regardless of the type instead of having to call one method for value types and another for value types? Probably not.
What happens (and I've done this lots and lots of times) is that we get caught up in how we want a certain class to look or behave for reasons that aren't related to the actual software that we're trying to write. In my experience this happens a lot when we're trying to write generic classes. Generic classes help us when we see unnecessarily code duplication in cases where the types we're working with don't matter (like if we had one class for a list of ints, another for a list of doubles, etc.)
Then when we get around to actually using the classes we've created we may find that our needs are not quite what we thought, and the time we spent polishing that generic class goes to waste.
If the types we're working with do require entirely different code then forcing the handling of multiple unrelated types into a single generic method is going to make your code more complicated. (Whenever we feel forced to use dynamic it's a good sign that something may have become overcomplicated.)
My suggestion is just to write the code that you need and not worry if you need to call different methods. See if it actually creates a problem. It probably won't. Don't try to solve the problem until it appears.
I've made some Middleware that logs all actions taken by a user within my application. Depending on the action taken, I need parse out some [FromBody] JSON into their respective key/value pairs for logging.
I need to deserialize my JSON within the middleware, but in order to do that, I need to send my DtoType along to the deserializer in order for it to parse out my key/values. I've got a method setup to do that, but I need to pass in a generic type because this will be different for every single action the user takes. (e.g. I have a UserDto, CustomerDto, etc...)
I've setup a dictionary in order to get the type that I need, however when I pass the var to my logging method to do the rest of the work, I get an error stating that this is not a type but a variable. This is true, however I have no idea how I'm supposed to get the type that I pulled out of my dictionary into the method generic type.
See my code below:
LoggingMiddleware.cs readonly dictionary
private readonly Dictionary<string, Type> _postDictionary = new Dictionary<string, Type>
{
{ "path/customers", typeof(CustomerPostDto) },
...//More entries//...
};
LoggingMiddleware.cs Invoke Method
public async Task Invoke(HttpContext context)
{
using (var streamCopy = new MemoryStream())
{
...//Do some stuff here//...
//Logging Actions
if (request.Path != "/")
{
if (request.Method == "POST")
{
Type T = _postDictionary[path];
logAction<T>(contextDto);
}
}
...//Do some stuff here//...
}
}
LoggingMiddleware.cs logAction Method
private void logAction<T>(object contextDto)
{
var dto = ControllerBase.ParseBody<T>(contextDto.Body);
...//Do some stuff here//...
}
EDIT: Following Example of Possible Duplicate - updated code
if (request.Method == "POST")
{
Type T = _postDictionary[path];
MethodInfo methodLogAction = typeof(LoggingMiddleware).GetMethod("logAction", BindingFlags.NonPublic);
MethodInfo generic = methodLogAction.MakeGenericMethod(T);
generic.Invoke(contextDto, null);
}
The above never returns anything for GetMethod other than null.
The exception is telling you exactly what is wrong.
Type T = _postDictionary[path];
This line of code pulls a Type instance from the dictionary and stores it in the variable, T. Then, you try to use it like this:
logAction<T>(contextDTO);
However, a generic method expects a non-variable argument between the angle-brackets. Types don't change at run-time; but the type arguments to a generic method can. (There are some compiler-specific nuances to that statement, but we'll ignore those for now.)
What you're essentially trying to get at is this:
logAction<SomeType>(contextDTO);
But if you want to store the type in a Dictionary, you'll have to pass that type as an argument to your method, and lose the generic capability:
public void logAction(Type type, object data)
{
// Log the data here
};
This is because the value of T is only known at runtime, not at compile time. You're going to have to reflect over T to get at its properties (as your question implies). In that event, you likely don't want a generic method, anyway.
If you're using json.net you could do something like:
public void LogAction<T>(string contextDto, Type type)
{
T obj = (T)JsonConvert.DeserializeObject(contextDto, type) ;
}
Or If I'm reading this wrong, and you and you want something like this, you could do this.
public void LogAction<T>(T obj)
{
}
public ActionResult Test([FromBody] Thing thing)
{
LogAction(thing);
}
I was able to get this with help of the Duplicate Post.
Within my Invoke method, I used GetMethod to find my method and assign a generic type based on my dictionary. Since it was a private method, I had to use both the BindingFlags.NonPublic & BindingFlags.Instance flags in order for it to find the method.
//Logging Actions
if (request.Path != "/")
{
if (request.Method == "POST")
{
Type T = _postDictionary[path];
MethodInfo methodLogAction = typeof(LoggingMiddleware).GetMethod("LogAction", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {typeof(object)}, null);
MethodInfo generic = methodLogAction.MakeGenericMethod(T);
generic.Invoke(this, new object[]{contextDto});
}
}
There is a difference between a Type (a class) and a generic type T. The T you are trying to get from your dictionary is simply a normal variable of the class Type, and not anything you can pass as a generic type parameter. You would probably have to change your approach a bit in order to achieve what you want without using reflection.
Approach 1. Let LogAction take a Type as a parameter and hope that there is an overloaded version that accepts such an argument:
private void LogAction(object contextDto, Type type) {
ControllerBase.ParseBody(contextDto.Body, type);
}
Or you can look into using a Func to control your parsing behavior better, something like
// Method to get a Func that can parse your object
private static Func<System.IO.Stream, T> GetParser<T>()
{
return (contextDto) => ControllerBase.ParseBody<T>(contextDto.Body);
}
// Use that in your dictionary
private Dictionary<string, Func<System.IO.Stream, object>> transformers = new Dictionary<string, Func<System.IO.Stream, object>>
{
{ "/myPath", GetParser<CustomerPostDto>() },
{ "/myPath-2", GetParser<CustomerPostDto>() }
};
// Now the LogAction method can just take the DTO that will be inferred from our parser
private void LogAction<T>(T dto)
{
...//Do some stuff here//...
}
// And call it as such
if (transformers.ContainsKey(path))
LogAction(transformers[path](context.Response.Body));
I would recommend it over reflection as it should give you more control in the long run.
You can get some more fun and abstraction by separating what is logging, and the other unrelated code:
// Return a logger with a specification on how to parse a stream from a body
private static TypeLogger CreateLogger<T>()
{
return new TypeLogger<T>((ctx) => ControllerBase.ParseBody<T>(contextDto.Body));
}
// Create a list with paths and loggers of specified type
private Dictionary<string, TypeLogger> loggers = new Dictionary<string, TypeLogger>
{
{ "/path1", CreateLogger<CustomerPostDto>() },
{ "/path2", CreateLogger<CustomerPostDto>() },
};
// Abstract base logger class that allows you to log from a requestbody
public abstract class TypeLogger
{
public abstract void Log(System.IO.Stream requestBody);
}
// An actual implementation to parse your dto using by using the parser previously specified
public class TypeLogger<T> : TypeLogger
{
// Parser to use when getting entity
public Func<System.IO.Stream, T> Parser { get; private set; }
// Constructor that takes sa func which helps us parse
public TypeLogger(Func<System.IO.Stream, T> parser) => Parser = parser;
// The actual logging
public override void Log(System.IO.Stream requestBody)
{
var dto = Parser(requestBody);
//...
}
}
// And usage
if (loggers.Contains(path))
loggers[path].Log(ctx.Response.Body);
I have a read model as IQueryable<CustomType>, I use this inside my Web application. A lot of time I need to extract from this read model different View Model.
I use to write extension method like:
public static ViewModelA AsViewModelA(this IQueryable<CustomType> query)
{
var vm = view
.Select(x => new ViewModelA
{
Something = x.Something
}).FirstOrDefault();
return vm;
}
public static ViewModelB AsViewModelB(this IQueryable<CustomType> query)
{
var vm = view
.Select(x => new ViewModelB
{
SomethingElse = x.SomethingElse
}).FirstOrDefault();
return vm;
}
This do the job but I don't like the mess generated with method names; a more generic way, something like this would be preferable:
query.AsViewModel<ViewModelA>()
I know that return type is not intended as method signature (so no overload applies) and I know that generic type is not sufficient to make an overload.
What I would is a mechanism to just simulate overloading based on generic type. This mechanism should avoid a main method with cascading if/then/else. There is a way? Maybe with dynamics?
One option is to have a map from the type to a conversion of CustomType to that type. So it would look something like:
private static readonly Dictionary<Type, Expression> Mappings =
new Dictionary<Type, Expression>
{
{ typeof(ViewModelA),
Helper<ViewModelA>(x => new ViewModelA { Something = x.Something }) },
{ typeof(ViewModelB),
Helper<ViewModelB>(x => new ViewModelB { SomethingElse = x.SomethingElse }) },
...
}
// This method just helps avoid casting all over the place.
// In C# 6 you could use an expression-bodied member - or add a
private static Expression<Func<CustomType, T>> Helper<T>
(Expression<Func<CustomType, T>> expression)
{
return expression;
}
public static T AsViewModel<T>(this IQueryable<CustomType> query)
{
Expression rawMapping;
if (!Mappings.TryGetValue(typeof(T), out rawMapping))
{
throw new InvalidOperationException("Or another exception...");
}
// This will always be valid if we've set up the dictionary properly
var mapping = (Expression<Func<CustomType, T>>) rawMapping;
return view.Select(mapping).FirstOrDefault();
}
You can make the dictionary construction a bit cleaner with a bit more up-front code.
Well, yes, you can use dynamic:
private static ViewModelA AsViewModelInternal(this IQueryable<CustomType> query,
ViewModelA dummy) { ... }
private static ViewModelB AsViewModelInternal(this IQueryable<CustomType> query,
ViewModelB dummy) { ... }
public static T AsViewModel<T>(this IQueryable<CustomType> query)
{
return (T)query.AsViewModelInternal(default(T));
}
Make sure to handle a non-existing overload, of course :) The easiest way is to add an overload that takes object as the last argument, so that you basically have a "fallback overload".
However, I wouldn't recommend that. One of the great benefits of generics is you get great compile-time checks. This generic method pretends to accept all possible T's, but it actually doesn't. It's the equivalent of taking object instead of ViewModelA/ViewModelB.
It's not like there's a world's difference between
query.AsViewModelB()
and
query.AsViewModel<ViewModelB>()
I'd only use the alternative if you often find yourself having to use a generic type argument when calling AsViewModel, i.e. when you don¨t know the specific 'type in advance.
I have a base class, SpecialClass. Lots of other classes inherit from it, like WriteSpecialClass and ReadSpecialClass. Instances of these classes are serialized and deserialized, after being casted to/from the base class. Therefore, I have lots of repetitious code like this (for serializing):
SpecialClass sc = null;
if (type.DisplayName == "Read") {
sc = new ReadSpecialClass();
} else if (type.DisplayName == "Write") {
sc = new WriteSpecialClass();
} else
throw new NotSupportedException("Type not supported");
String xml = SerializeToXML(sc);
.. and deserializing:
SpecialClass sc = null;
sc = (SpecialClass)DeserializeFromXML(xml);
switch (someVariableThatDicatesTypeOfSpecialClass) {
case "Read":
sc = (ReadSpecialClass)sc;
break;
case "Write":
sc = (WriteSpecialClass)sc;
break;
}
One more important piece of info: SpecialClass has a bunch of abstract methods defined which each class that inherits from it needs to implement. All the classes which inherit from it conform to the methods, but return different things, so each class is not the same.
I can post my serialization or deserialization methods if needed.
I would like to try and simplify this so that I don't have to specify each SpecialClass-derived class (like ReadSpecialClass). Is there any way to do this? The only way I can think of is duck-typing. Thanks for your help,
Have you considered a serialize() method in SpecialClass? That way if there are some special considerations you can override the base.serialize method and take care of any unique needs. In this way it already knows what it is and the conditional isn't necessary.
Another thing to consider is maybe a helper class with a facade pattern. Then you can have a a method called "public SpecialClass DeserializeSpecialClass()". Then instead of casting the type in the deserializer you could cast it at the target. If you find you are doing too much casting then maybe consider adding abstract methods to the base class that will be realized in the derived class.
Hope this helps.
For serializing, you can use some sort of lookup:
public class SpecialClass
{
private static Dictionary<string, Func<SpecialClass>> factories =
new Dictionary<string, Func<SpecialClass>>();
static SpecialClass()
{
factories["Read"] = () => new ReadSpecialClass();
factories["Write"] = () => new WriteSpecialClass();
}
public static SpecialClass CreateByName(string name)
{
Func<SpecialClass> factory;
if (!factories.TryGetValue(name))
throw new ArgumentException("name", "\"" name +
"\" is not a recognized subclass of SpecialClass.");
return factory();
}
}
For deserialization, these two lines:
sc = (ReadSpecialClass)sc;
sc = (WriteSpecialClass)sc;
perform no actual conversion. The only thing they will do is throw an exception if the object referenced by sc is not of the appropriate type. What you are doing here is roughly the same thing as:
object a = "foo";
a = (string)a;
Sure, the cast will succeed. But it does not in any way modify the object pointed to by a. All it really does is verify that this object is already a string.
if (sc is WriteSpecialClass)
{
sc = (WriteSpecialClass) sc;
}
else if (sc is ReadSpecialClass)
{
sc = (ReadSpecialClass) sc;
}
else
{
throw new NotSupportetException("Type not Supportet");
}
If you're not concerned about performance, you can use reflection to initialize the types whose name contains that type name.
SerializeToXML() takes the base class SpecialClass as a parameter, so it shouldn't distinguish the difference between the derived classes ReadSpecialClass and WriteSpecialClass. Why don't you have SerializeToXML() as an instance method of the base class?
Rule 1./ Your derived classes should be responsible for serializing and deserializing themselves, as they should be the only ones that have intimate knowlege of the additional data that is stored in the XML Doc.
So from a ploymorphic point of view (note your code above is not polymorphic) you would do something like
public class SpecialClass
{
public virtual XElement SerializeToXML()
{
// Base impl
}
}
public class YourDerivedClasses
{
public override XElement SerializeToXML()
{
//derived implementation
}
}
Pretty straight forward. But the problem you have is not one of serialization or polymorphic behaviour, it's one of instantiation of the correct type from the XML.
One way to solve that problem is to have some key in your XML doc that specifies the type that saved it, and register a factory responsible for construction of the derived type indexed by that key (attributes are good for that kind of registration), once the derived type is constructed use it to deserialize the xml.
Note, your factory could also be a static method on the Base class.
Something like, (untested of course)....
public class SpecialClass
{
***snip
public static IEnumerable<SpecialClass> GetAllClasses(XElement xml)
{
IDictionary keyedtypes = GetKeyedTypesDictUsingReflection() // the registered factories
foreach(var x in xml.Elements("YourClassesNode"))
{
string key = //get key from xml
yield return keyedTypes[key].DeserializeFromXML(x);
}
}
}
I have throughout my application many methods where I load collections. They all (actually most with a couple of differentials) follow the following pattern:
public BaseCollection<ObjectType1> LoadObjectType1(EventHandler handleEvent)
{
var myQuery = ObjectType1.Load(MyServiceContext);
return new DataManager<ObjectType1>().GetData(myQuery , handleEvent, MyServiceContextt);
}
public BaseCollection<ObjectType2> LoadObjectType2(EventHandler handleEvent)
{
var myQuery = ObjectType2.Load(MyServiceContext);
return new DataManager<ObjectType2>().GetData(myQuery , handleEvent, MyServiceContextt);
}
public BaseCollection<ObjectType3> LoadObjectType3(EventHandler handleEvent)
{
var query = ObjectType3.Load(MyServiceContext);
return new DataManager<ObjectType3>().GetData(query, handleEvent, MyServiceContextt);
}
Where ObjectType# are my business objects, e.g. Employee, Department, etc.
I would like to convert these to harness Generics.
Any advice will be greatly appreciated.
You can always create version of these functions that take a generic argument themselves. However, since there is no argument that can allow the compiler to infer the type of the generic argument, you will always have to supply it in the call.
The main issue, is that you're using a static Load method that is implemented on each object type. You would have to pass this in to the call as a delegate:
public BaseCollection<T> Load<T>(EventHandler handleEvent, Func<QueryType> querySelector)
{
var myQuery = querySelector(MyServiceContext);
return new DataManager<T>().GetData(myQuery , handleEvent, MyServiceContext);
}
When calling these version, you would have to specify the type T, as well as pass in a delegate that will return the query object you use to load your data (since it's type specific):
LoadDepositionSampleTypeItemSource<Department>( handler, Department.Load );
EDIT: So, now that you've updated your question I think I understand it a bit better. There's no reason you can't collapse the different methods down to a single overload. If you can refactor the implementation so that the query is not retrieved from the object type, you may be able to improve and consolidate things further. A factory pattern may make things cleaner and more maintainable:
public BaseCollection<T> Load<T>(EventHandler handleEvent)
{
var myQuery = QueryManager.GetQuery<T>(MyServiceContext);
return new DataManager<T>().GetData(myQuery , handleEvent, MyServiceContext);
}
Do you mean you want the methods to be generic? Something like this?
public BaseCollection<T> LoadObject<T>(EventHandler handleEvent)
{
var myQuery = BusinessUtil.Load<T>(MyServiceContext);
return new DataManager<T>().GetData(myQuery, handleEvent, MyServiceContext);
}
Of course, the problem with this is that you can’t easily call the separate static .Load() methods you already have. You will have to declare a single static generic .Load() method, which can return objects of any of your business types. Something like this maybe:
public static class BusinessUtil
{
public static T Load<T>(ServiceContext context)
{
if (typeof(T) == typeof(Object1))
return (T) Object1.Load(context);
if (typeof(T) == typeof(Object2))
return (T) Object2.Load(context);
// ... etc.
}
}
Alternatively, you can require an extra parameter on LoadObject<T> that specifies how to create such an object:
public BaseCollection<T> LoadObject<T>(EventHandler handleEvent,
Func<ServiceContext, T> generator)
{
var myQuery = generator(MyServiceContext);
return new DataManager<T>().GetData(myQuery, handleEvent, MyServiceContext);
}
// ...
var obj = LoadObject(handleEvent, Object1.Load);
This is assuming that myQuery needs to be of type T, which unfortunately the code in your question doesn’t reveal. If it needs to be a different type, maybe some sort of Query<T>?, then you will need to change the T inside the Func<> (and the return type of BusinessUtil.Load) to that too.
You could use Reflection:
public BaseCollection<T> LoadGeneric<T>(EventHandler handleEvent)
{
var myQuery = (YourQueryType)typeof(T)
.GetMethod("Load")
.Invoke(null, new object[] { MyServiceContext });
return new DataManager<T>().GetData(myQuery , handleEvent, MyServiceContextt);
}
But I think refactoring the code (maybe using single static method as Timwi suggested) would be a better choice.