I'm struggling with method overload in C#.
I have a few classes inheriting form a generic one
// I can not touch the implementation of these classes
class GenericDataType {}
class ProductDataType : GenericDataType {}
class ContentDataType : GenericDataType {}
And a class that have a method that iterates on a list of these classes. This method should behave differently in base of what is the type of the item that the cycle is currently consuming
class DataTypeParser {
public List<ParserdType> parseAll(List<GenericDataType> list) {
var resultList = new List<ParserdType>();
foreach(var item in list) {
// if item is a ProductDataType do something
// if item is a ContentDataType do something else
// else do some generic stuff...
// then add to resultList the current processed item
}
}
}
I think that the most natural approach is to add a virtual method in GenericDataType and then add an implementation of such method in the sub classes, but I can't touch any class except for DataTypeParser.
I don't want to add a bunch of if else in the code, I would rather use some polymorphic stuff in order to easily handle different implementation of that GenericDataType.
So my solution was to add some overloaded methods in DataTypeParser
class DataTypeParser {
public List<ParserdType> parseAll(List<GenericDataType> list) {
var resultList = new List<ParserdType>();
foreach(var item in list) {
var parsed = parse(item);
if(parsed != null){
resultList.Add(parsed);
}
}
}
public ParserdType parse(ProductDataType o){
// do something
// ...
return new ParserdTypeProduct();
}
public ParserdType parse(ContentDataType o){
// do something else
// ...
return new ParserdTypeContent();
}
public ParserdType parse(GenericDataType o){
return null;
}
}
But it doesn't work because C# seems to call only the function with generic parameter.
What am I missing?
I'm pretty a noob, particularly for C#, so it's easy that I'm missing something important, even some link may be very helpful.