If you want to simplify it, you can use an expression to dynamically call correctly.
//Cache the generated method for re-use later, say as a static field of dictionary. It shouldn't grow too-big given the number of overloads of Write. private static Dictionary<Type, Action<BinaryWriter, object>> _lambdaCache = new Dictionary<Type, Action<BinaryWriter, object>>(); //... if (!_lambdaCache.ContainsKey(fi.FieldType)) { var binaryWriterParameter = Expression.Parameter(typeof(BinaryWriter)); var valueParameter = Expression.Parameter(typeof(object)); var call = Expression.Call(binaryWriterParameter, "Write", null, Expression.Convert(valueParameter, fi.FieldType)); var lambda = Expression.Lambda<Action<BinaryWriter, object>>(call, binaryWriterParameter, valueParameter).Compile(); _lambdaCache.Add(fi.FieldType, lambda); } var write = _lambdaCache[fi.FieldType]; write(bw, fi.GetValue(obj));
What we are doing here is dynamically generating code to make the call you need for binary writing. This sounds a lot more complicated than what we do, but we create an expression for the "Write" method for BinaryWriter . We also dynamically apply it using Expression.Convert , so the correct Write overload is called. We take two BinaryWriter parameters and a value for writing. Finally, we compile lambda and cache for this type for reuse later.
Depending on your needs, this will be much faster than using reflection over BinaryWriter .
source share