HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Is there a more concise and/or readable way to write the following method?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
readablethemethodmorewaywriteconcisefollowingandthere

Problem

Preface: I'm starting to learn C# and I don't want to port any of my bad habits from other languages, so I'm following convention wherever possible.

Using the default Visual Studio code formatting, this relatively simple function requires 14 lines of code.

public void add(int[] values, Func transform = null)
{
    foreach (int v in values)
    {
        if (transform == null)
        {
            add(v);
        }
        else
        {
            add(transform(v));
        }
    }
}


My first thought was to use the ?? operator to do something like the following snippet, but apparently that's gibberish.

public void add(int[] values, Func transform = null)
{
    foreach (int v in values)
    {
        add(transform(v) ?? v);
    }
}


Is there a more concise and/or readable way to write the following method?

Solution

There are at least two answers.
The short one:

public void add(int[] values, Func transform = null)
{
    foreach (int v in values)
        add( (transform != null) ? transform(v) : v);
}


The efficient one:

public void add(int[] values, Func transform = null)
{
    if( transform != null) 
      foreach (int v in values)
        add( transform(v));
    else
      foreach (int v in values)
        add( v);
}


Not nice, but you wanted a short version.

Maybe someone has a LINQ at hand which does this even better.

Code Snippets

public void add(int[] values, Func<int, int> transform = null)
{
    foreach (int v in values)
        add( (transform != null) ? transform(v) : v);
}
public void add(int[] values, Func<int, int> transform = null)
{
    if( transform != null) 
      foreach (int v in values)
        add( transform(v));
    else
      foreach (int v in values)
        add( v);
}

Context

StackExchange Code Review Q#39427, answer score: 3

Revisions (0)

No revisions yet.