Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an overloaded function by using a generic variable as a parameter

I want to extend the BinaryWriter class to be able to write a list to a stream. I want to do this with multiple types of lists. I set up this generic function as an extension

public static void Write<T>(this BinaryWriter source, IEnumerable<T>items)
{
     foreach (T item in items)
          source.Write(item)//This doesn't work
} 

Is this at all possible? I know write can handle all the built in types. I know there is the ability to constrain T to certain types, but I couldn't do it for int and double.

I only need it to work for ints, doubles, and bytes.

like image 943
Bear Avatar asked Jul 27 '26 15:07

Bear


2 Answers

I know there is the ability to constrain T to certain types

Unfortunately, the compiler has no idea that T is one of these types, so it has to complain.

I only need it to work for ints, doubles, and bytes.

You can make three overloads then:

public static void Write(this BinaryWriter source, IEnumerable<int>items) {
    foreach (var item in items)
        source.Write(item);
}
public static void Write(this BinaryWriter source, IEnumerable<double>items) {
    foreach (var item in items)
        source.Write(item);
}
public static void Write(this BinaryWriter source, IEnumerable<byte>items) {
    foreach (var item in items)
        source.Write(item);
}
like image 155
Sergey Kalinichenko Avatar answered Jul 29 '26 03:07

Sergey Kalinichenko


dasblinkenlight's solution is probably the way to go, but here's an alternative:

public static void Write(this BinaryWriter source, IEnumerable items)
{
     foreach (dynamic item in items)
          source.Write(item); //runtime overload resolution! It works!
}

For more info on dynamic, see the documentation.

like image 26
Tim S. Avatar answered Jul 29 '26 03:07

Tim S.