I am engaged in data analysis and have come across this problem. Say we want to analyze the structure of byte[] . I want to wrap C # code that does this in a static method.
Source code (I will redo part):
public class DiagnosticUndefined : BaseDiagnostic { StructDiagnosticUndefined bufferAllocation; public DiagnosticUndefined(byte[] buff) { bufferAllocation = (StructDiagnosticUndefined)DiagnosticUtil.parseStruct(buff, typeof(StructDiagnosticUndefined)); } }
I would like to use a common function for this, but how to proceed? Consider:
public static class Util { public static T Convert<T>(byte[] data) {...} public static void Convert<T>(byte[] data, out T structure) {...} }
The first one is more related to the normal procedure, but has the disadvantage that the compiler cannot infer the data type, so my call will look like this:
SomeStruct s; s = Util.Convert<SomeStruct>(data);
Another approach is as follows:
SomeStruct s; Util.Convert(data, out s);
I like the second approach because it delegates type inference to the compiler, i.e. fewer runtime errors. On the other hand, I try to avoid using the out parameter supported by MSDN: http://msdn.microsoft.com/en-us/library/ms182131.aspx . I’m all for the “do not solve simple problems in a complicated way” paradigm, but I cannot differentiate this time ...
Any hints, opinions?
Update
The code examples are simplified, the variable is actually a member, so I cannot go on one line. I also use Marshalling to convert data to a structure:
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned); T output = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); handle.Free();