3
\$\begingroup\$

I currently am making a small application where a user will enter their ID which needs to be in a certain format. When entered in the wrong format, different output errors are produced.

I currently output errors like this:

public void errorLogger(string error)
        {
            errors += error + Environment.NewLine + "<br>";
        }

I have read that using += is not a great operator to use. Alternatively I have thought this may be better:

public void errorLogger(string key, string err)
        {
            if(!String.IsNullOrEmpty(err))
            output.Add(key, err);
        }

but then I basically do the same thing later:

    string keys = "";
    foreach (KeyValuePair<string, string> entry in core.errorLogger())
    {
        keys += entry.Key + ":       " + entry.Value + "<br>";
    }

Is there a cleaner way to output errors? The output is injected under the submit button into:

errorSpan.InnerHtml = (keys);

This is what I ended up using going off of Charles' response to AWinkle

public void logError(string err, string desc)
                {
                    if(!String.IsNullOrEmpty(desc))
                        errors.AppendFormat("{0,10}:&nbsp;{1}<br>", err, desc);
                }
public string getErrors()
            {
                return errors.ToString();
            }

Then :

errorspan.InnerHtml = (core.getErrors());
\$\endgroup\$
  • \$\begingroup\$ Please put your full code or at least the parts needed to in this code snippet, errors and output for example \$\endgroup\$ – Sleiman Jneidi Nov 7 '14 at 22:04
4
\$\begingroup\$

Using the StringBuilder class will typically be better for looped string building.

string keys = "";
foreach (KeyValuePair<string, string> entry in core.errorLogger())
{
    keys += entry.Key + ":       " + entry.Value + "<br>";
}

turns into

StringBuilder keys = new StringBuilder();
foreach (KeyValuePair<string, string> entry in core.errorLogger())
{
    keys.AppendFormat("{0}:&nbsp;{1}<br>", entry.Key, entry.Value);
}

Then you take errorSpan.InnerHtml = (keys); and change it to errorSpan.InnerHtml = (keys.ToString());

Alternatively, you could use this to replace the dictionary as CharlesNRice suggests.

StringBuilder keys = new StringBuilder();

 public void errorLogger(string key, string err)
    {
        if(!String.IsNullOrEmpty(err))
        keys.AppendFormat("{0}:&nbsp;{1}<br>", key,err);
    }
\$\endgroup\$
  • 3
    \$\begingroup\$ In this situation StringBuilder for a few rare error messages is likely to be a premature optimization (if it is an optimization at all). \$\endgroup\$ – James Snell Nov 8 '14 at 1:37
  • \$\begingroup\$ Why have the dictionary in the first place if you are going to use string builder and have a method to format the string and add to the string builder right away. \$\endgroup\$ – CharlesNRice Nov 9 '14 at 2:50
  • \$\begingroup\$ @CharlesNRice I added an alternative version based on your comment. You make a valid point, that a dictionary might be overkill/under-optimized (it probably is). \$\endgroup\$ – AWinkle Nov 10 '14 at 17:43
4
\$\begingroup\$

This answer is another way of achieving the same. I am not claiming that this is the cleanest or most performant way but it certainly works.

List<string>

When you're using this method to store all the error messages, you can use the Enumerable.Aggregate<TSource> method:

var errors = new List<string>();

errors.Add("This is error message 1.");
errors.Add("Another error!");

var message = errors.Aggregate((c, n) => c + Environment.NewLine + n);

Outputted, message will now have following value:

This is error message 1.

Another error!

You can also look into the String.Join method. The message is built up like this:

var message = String.Join(Environment.NewLine, errors);

This will create the same output.

Dictionary<int, string>

In a situation where you store an integer as a key and the message as a string in a Dictionary<int, string>, you can also the String.Join method:

var errors = new Dictionary<int, string>();

errors.Add(1, "This is error message 1.");
errors.Add(2, "Another error!");

var message = String.Join(Environment.NewLine, errors.Select(x => String.Format("{0}: {1}", x.Key, x.Value)));

The result looks like this:

1: This is error message 1.

2: Another error!

\$\endgroup\$
  • \$\begingroup\$ I'm a really big fan of this because everyone needs to use Linq and Lambda more. \$\endgroup\$ – AWinkle Nov 12 '14 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.