Can I create a generic method that accept two types. The attributeType
and ts_attributeType
do not share any common parent class although they do have the same fields.
Is this possible? Or is there some way I can achieve this?
private static void FieldWriter<T>(T row)
where T : attributeType, ts_attributeType
{
Console.Write(((T)row).id + "/" + (((T)row).type ?? "NULL") + "/");
}
I have seen this answer from Jon Skeet, however I am not certain if it also applies to my question.
Some further background:
Both attributeType
and ts_attributeType
have been created using the xsd.exe tool; and are are partial classes.
No, you can't. The simplest alternative is to simply write two overloads, one for each type. You can always extract the common code if you want to avoid repeating yourself too much:
private static void FieldWriter(attributeType row)
{
FieldWriterImpl(row.id, row.type);
}
private static void FieldWriter(ts_attributeType row)
{
FieldWriterImpl(row.id, row.type);
}
// Adjust parameter types appropriately
private static void FieldWriterImpl(int id, string type)
{
Console.Write(id + "/" + (type ?? "NULL") + "/");
}
Alternatively, you could use dynamic typing if you're using C# 4.
(A better solution would be to give the two classes a common interface if you possibly can - and rename them to follow .NET naming conventions at the same time :)
EDIT: Now that we've seen you can use partial classes, you don't need it to be generic at all:
private static void FieldWriter(IAttributeRow row)
{
Console.Write(row.id + "/" + (row.type ?? "NULL") + "/");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With