Search code examples
c#genericsout

'out' parameter versus generic/template argument: best practice


I'm doing some data parsing and came across this issue. Say we want to parse some byte[] to a structure. I want to wrap the C# code that does that into a static method.

The original code (I am reworking a piece) read:

public class DiagnosticUndefined : BaseDiagnostic
{
    StructDiagnosticUndefined bufferAllocation;

    public DiagnosticUndefined(byte[] buff)
    {
        bufferAllocation = (StructDiagnosticUndefined)DiagnosticUtil.parseStruct(buff, typeof(StructDiagnosticUndefined));
    }
}

I'd like to use a generic function for that, 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 is more inline with normal procedure but is has the downside that the compiler cannot infer the datatype so my call will look like this:

SomeStruct s;
s = Util.Convert<SomeStruct>(data);

The other approach is this:

SomeStruct s;
Util.Convert(data, out s);

I like the second approach as it delegates the type inference to the compiler i.e. less runtime errors. On the other hand I tend to avoid use of the out parameter as supported by MSDN: http://msdn.microsoft.com/en-us/library/ms182131.aspx. I'm all for the "don't solve simple problems in a complex way" paradigm but I can't differentiate this time...

Any hints, opinions?

Update

The code examples are simplified, the variable is actually a member so I can't go 'one-line'. Also I am using Marshalling to convert the data into a structure:

GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
T output = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();

Solution

  • EDIT Suggested by @Nebula

    The first case, seems perfectly valid one:

    var s = Util.Convert<SomeStruct>(data);
    

    Use out when you want somethign back from the call, but not for declarative purposes.