I am writing some feature of System.IO.BinaryWriter . This writer should be able to handle integral types, including Enum and , as well as the collection of these types .
abstract class MyBinaryWriter {
What is the best approach to solve this problem? There is a better solution using generics than writing overloads for each type of integral, and each type of enum that I want to process? A possible solution follows, but I donβt like it so much and have potential performance problems.
#region Methods: Complex Types: Writing public virtual void Write<T>(ICollection<T> collection) where T : IConvertible { // first write the 32-bit-unsigned-length prefix if (collection == null || collection.Count == 0) { Write((uint)0); } else { Write((uint)collection.Count); // get the method for writing an element Action<T> write = null; var type = typeof(T); if (type.IsEnum) type = Enum.GetUnderlyingType(type); switch (Type.GetTypeCode(type)) { case TypeCode.Byte: case TypeCode.SByte: write = (x => Write((byte)(IConvertible)x.ToByte(null))); break; case TypeCode.Int16: case TypeCode.UInt16: write = (x => Write((ushort)(IConvertible)x.ToUInt16(null))); break; case TypeCode.Int32: case TypeCode.UInt32: write = (x => Write((uint)(IConvertible)x.ToUInt32(null))); break; case TypeCode.Int64: case TypeCode.UInt64: write = (x => Write((ulong)(IConvertible)x.ToUInt64(null))); break; default: Debug.Fail("Only supported for integral types."); break; } // then write the elements, if any foreach (var item in collection) write(item); } }
source share