Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a generic method that accepts two different types in C#

Tags:

c#

c#-4.0

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.

like image 520
Ahmad Avatar asked Sep 14 '25 21:09

Ahmad


1 Answers

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") + "/");
}
like image 150
Jon Skeet Avatar answered Sep 16 '25 11:09

Jon Skeet