Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top