0

The following function uses a very long and complex type Long_complex_type and it's hard to read. I tried to add parameter to the function but it doesn't work and var doesn't support lambda expression. What's the best way to make the code more readable besides using-alias-directive? (I don't want to create many type aliases, ideally the type can be inferred)

private void MyFunction()
{
    Func<Long_complex_type> dowork = () => _service.GetSomething(.....);
    Action<Long_complex_type> then = (Long_complex_type l) => { _view.DoSomething(l); };
    ....... 
}
ca9163d9
  • 27,283
  • 64
  • 210
  • 413

1 Answers1

4

Simply create a factory method which will allow you to use type inference:

public static Func<T> CreateDelegate<T>(Func<T> function)
{
    return function;
}
public static Action<T> CreateDelegate<T>(Action<T> action)
{
    return action;
}

You can now write:

var dowork = CreateDelegate(() => _service.GetSomething(.....));
var then = CreateDelegate((Long_complex_type l) => { _view.DoSomething(l); });
Servy
  • 202,030
  • 26
  • 332
  • 449
  • Almost perfect. However, still have to write the type of `l`, which may be mandatory. – ca9163d9 Feb 03 '16 at 22:40
  • @dc7a9163d9 You could infer it if you had an object of that type, or an object that used it as a part of it's type (through generics). You can't infer the type of something you know nothing about, obviously. – Servy Feb 03 '16 at 23:03
  • Theoretically the type of `l` can be inferred from `_view.DoSomething(l)`. – ca9163d9 Feb 04 '16 at 00:10
  • @dc7a9163d9 No, it cannot. – Servy Feb 04 '16 at 00:19