Programming Practices – Is It Good Practice to Declare a Function Inline in C#?

cprogramming practices

I'm writing a method and depending on a config field I need to change where I get my data from. What this results in me having to write code that looks like this:

List<string> result = new List<string>();
if (configField)
{
    result.Add(fieldA);
}
else
{
    result.Add(...BusinessLogic...);
}

I'll have to write that if statement many many times so of course I want to turn it into a method instead so I can just write result.Add(newMethod(configField, fieldA, dataForBusinessLogicToParse)). This method would be useless to anyone not writing the specific method I'm writing so does it make sense to declare this method as a separate private method or can I just declare it inline as a delegate like this:

Func<Enum, int, int> newMethod =
    (configField, fieldA, dataForBusinessLogicToParse) => ...businessLogic...

I'm worried declaring it inline might make the code more difficult to understand but I think it makes the class cleaner.

Best Answer

As far as I know, declaring a helper method as a lambda like this is not commonly done in C#, so I would advise against doing this unless you have a good reason.

Good reasons include:

  • The lambda could do something a separate method can't, like closing over a local variable or using anonymous type.
  • Others in your team agree with you that this is a good practice.

That being said, starting with C# 7.0, C# supports local functions, which are similar to such helper lambdas, but generally better: they have more succinct syntax and are more efficient. So if you used a local function for this purpose, I think that would be perfectly fine.