Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generics not recognizing type

Tags:

c#

.net

generics

I can't figure out why the following code returns a Cannot resolve method Write(T) - it seems unambiguous to me:

    private static void WriteToDisk<T>(string fileName, T[] vector)
    {
        using (var stream = new FileStream(fileName, FileMode.Create))
        {
            using (var writer = new BinaryWriter(stream))
            {
               foreach(T v in vector) writer.Write(v);
                writer.Close();
            }
        }
    }

I would like to define a generic binary write method that can deal with vectors of, e.g., int[], long[] or double[].

like image 439
Ze Jibe Avatar asked Dec 04 '22 13:12

Ze Jibe


1 Answers

Which overload of Write() to call will be determined at compile time, not at runtime. BinaryWriter would need a Write(object) overload (or a Write<T>(T) generic overload) to allow calling the method this way. This error (correctly) indicates that it has neither.

You will need to write your own wrapper method that accepts an object (or a generically-typed argument) and inspects its type to determine which BinaryWriter.Write() overload to call.

like image 94
cdhowie Avatar answered Dec 15 '22 10:12

cdhowie