I have a util class (C#) where I have a static method that takes a certain type of object and brings up a web service to get further data. I would like to support other object types and to not replicate the code, i.e. add multiple similar methods, I am thinking the Generic route would be best.
For example, let’s say I have:
public static void GetData(Building building)
{
var webClient = new WebClient();
var wrapper = new WrapperClass(building);
if (building.Distance.HasValue)
{
structure = new Structure((decimal)building.Length.Value, (decimal)building.Height.Value);
}
... // and so on ...
instead of creating another method(s) like so:
public static void GetDataForBridge(Bridge bridge)
{
var webClient = new WebClient();
var wrapper = new WrapperClass(bridge);
if (bridge.Distance.HasValue)
{
structure = new Structure((decimal)bridge.Length.Value, (decimal)bridge.Height.Value);
}
// ...
I am not sure how to do this using Generics. Can anyone please give me some tips or advice?
In this case, Bridge and Building would have to implement the same interface, say, IObjectWithHeightAndWidth. You’d then specify this interface as a constraint on the type parameter of your generic method.
(Or, instead of a common interface, the classes could share a common base class.)
As other posters have pointed out, though, you might not need generics at all. You only would need generics if you subsequently need to have a strongly-typed reference to the object as a
BridgeorBuilding— for example if you need to call another generic method in the method we’re discussing.