Thursday 24 March 2011

C# is soooo verbose

I have this:
List<ReportItem2> value = new List<ReportItem2>();
IEnumerable<MComponentDetails> components = SwapUtils.GetBasketComponents(swap);
foreach (MComponentDetails detail in components)
{
    string sedol = InstrumentUtils.GetSedol(detail.fSicovam);
    string instrName = InstrumentUtils.GetInstrName(detail.fSicovam);
    value.Add(new ReportItem2(sedol, instrName, columnConfig));
}

and I'd like to have this:
List<ReportItem2> value = new List<ReportItem2>();
IEnumerable<MComponentDetails> components = SwapUtils.GetBasketComponents(swap);
value.AddRange(Functional.map(sec(columnConfig), components));

but there are two problems. One is that the code required in order to build
sec
and enable it to take a parameter (instead of simply being a delegate) is far too much; the second is that, unbelievably, the compiler will not implicitly cast from
IEnumerable<MComponentDetails>
to
IEnumerable<object>
Unbelievable!

By way of illustrating the verbosity of C#, here is my preliminary version of the loop innards:

private class sec
{
    private static ExportColumnConfiguration _config;
    public static Functional.fn f(ExportColumnConfiguration config)
    {
        _config = config;
        return sec_func;
    }

    private static Functional.fn sec_func = CreateReportItem2FromSecurity;
    private static ReportItem2 CreateReportItem2FromSecurity(MComponentDetails detail)
    {
        string sedol = InstrumentUtils.GetSedol(detail.fSicovam);
        string instrName = InstrumentUtils.GetInstrName(detail.fSicovam);
        return new ReportItem2(sedol, instrName, _config);
    }
}


Aha, but I discover that C# 2.0 supports anonymous delegates which are, effectively, lambdas and closures.

Splendid!

No comments:

Post a Comment