Found the following code in one open source project, and I am amazed how original coder used local and static local functions in here:
public static Win32Error CallMethodWithTypedBuf<TOut, TSize>(SizeFunc<TSize> getSize, PtrFunc<TSize> method, out TOut result, Func<IntPtr, TSize, TOut> outConverter = null, Win32Error? bufErr = null) where TSize : struct, IConvertible
{
TSize sz = default;
result = default;
var err = (getSize ?? GetSize)(ref sz);
if (err.Failed && (bufErr == null || bufErr.Value != err) && !buffErrs.Contains(err)) return err;
using (var buf = new SafeHGlobalHandle(sz.ToInt32(null)))
{
err = method(buf.DangerousGetHandle(), ref sz);
if (err.Succeeded)
result = (outConverter ?? Conv)(buf.DangerousGetHandle(), sz);
return err;
}
Win32Error GetSize(ref TSize sz1) => method(IntPtr.Zero, ref sz1);
static TOut Conv(IntPtr p, TSize s) => p == IntPtr.Zero ? default : p.Convert<TOut>(Convert.ToUInt32(s));
}
So I've rewritten to something that would actually have logic in one place, and would work even in older compilers (As it would be written 10 years ago). To realize that following code is actually less in size, consumes less call stack, and could be better optimized by if-branch prediction:
public static Win32Error CallMethodWithTypedBuf<TOut, TSize>(SizeFunc<TSize> getSize, PtrFunc<TSize> method, out TOut result, Func<IntPtr, TSize, TOut> outConverter = null, Win32Error? bufErr = null) where TSize : struct, IConvertible
{
TSize sz = default;
result = default;
var err = (null != getSize ? getSize(ref sz) : method(IntPtr.Zero, ref sz));
if (err.Failed && (bufErr == null || bufErr.Value != err) && !buffErrs.Contains(err)) return err;
using (var buf = new SafeHGlobalHandle(sz.ToInt32(null)))
{
err = method(buf.DangerousGetHandle(), ref sz);
if (err.Succeeded)
{
IntPtr p = buf.DangerousGetHandle();
result = (null != outConverter) ? outConverter(p, sz) : (p == IntPtr.Zero ? default : p.Convert<TOut>(Convert.ToUInt32(sz)));
}
return err;
}
}
So I'am more than little confused why would anyone use local and static functions, as original coder did use. At this point I think people are angry and do not know what to do with themselfs, and started making mess at global scale. Please tell me that I am wrong, and that we all should use local and static local functions immediately all over our codes?