2

In my program, I will get a var object at run time and I would like to write it to a binary file, but I couldn't write var variable by using BinaryWriter. It gives a compile error that cannot convert from 'object' to 'bool'. How to solve it?

BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)
var obj = Convert.ChangeType(property.GetValue(objectToWrite, null), property.PropertyType);
writer.Write(obj); //Compile error
RobinAtTech
  • 1,299
  • 3
  • 22
  • 48

2 Answers2

2

var in this case will resolve to object, since that is what GetValue returns. There is no overload of BinaryWriter.Write that accepts object. What you want next depends on a few things:

  • if your intent is to write a very simply value (a single bool, int, etc - something supported by BinaryWriter) to a file, then you will have to switch on the type of that simple value; a cheeky way to do that is to use dynamic, which will figure that out at runtime:

    writer.Write((dynamic)obj); // not great, but should work
    
  • if your intent is to write a complex piece of data (a class / struct etc) then you shouldn't be using BinaryWriter - you should be using a serializer. Perhaps BinaryFormatter (although that has some serious kinks which makes me reluctant to recommend it) or protobuf-net, or similar

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • @Rambo out of curiosity... what is the actual data type here? – Marc Gravell May 22 '13 at 11:03
  • I am reading from a database. Database tables may contain int, float, string variables. I have to decide it dynamically and write it to a binary file – RobinAtTech May 22 '13 at 11:05
  • Why you are saying so? Actually I will write all the properties in the class instance in a loop or else do you recommend to write all the properties once? – RobinAtTech May 22 '13 at 11:12
  • Actually my requirement is, writing all the memeber variable values to a binary file – RobinAtTech May 22 '13 at 11:21
  • @Rambo I *strongly* suggest you look into pre-rolled serialization libraries; doing this by hand is not for the faint hearted – Marc Gravell May 22 '13 at 14:58
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/30438/discussion-between-rambo-and-marc-gravell) – RobinAtTech May 22 '13 at 19:48
0
BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create);
var obj = Convert.ChangeType(property.GetValue(objectToWrite, null), property.PropertyType);
writer.Write(obj);

Try to use obj instead of var.

Praveen
  • 55,303
  • 33
  • 133
  • 164
Ramesh
  • 376
  • 2
  • 6
  • 11