0

I've been trying to enumerate through a properties of a class and getting their values in a List of strings. But i faced a problem where i get a NullReferenceException when the value is null from the properties

I Managed to Fix that by that solution, but still i don't see that as a clean code.

I Wonder if this can be implemented in a cleaner and more professional way.

    private int CalculateScore()
    {
        var score = 0;
        var answers = new List<string>();
        foreach (var prop in typeof(TypesSheet).GetProperties())
        {
            // WHEN STRING IS MISSING IT BREAKS
            try
            {
                var answer = prop.GetValue(_typesSheet).ToString();
                answers.Add(answer);
            }
            catch
            {
                continue;
            }


        }

        if (_gameMode == GameMode.SinglePlayer)
        {
            foreach (var answer in answers)
            {
                if (string.IsNullOrEmpty(answer))
                    continue;

                score = score + 10;
            }

            return score;
        }
  }
Omar Alaa
  • 141
  • 2
  • 13
  • A try catch is a terrible idea. You end up swallowing Fatal Exceptions. And swallowing those is a deadly sin of exception handling: https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/ | https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET This exception is very much a boneheaded one. The obvious solution would be to check for null before you use it. Aside from the simple code `if (x != null)`, there is a bunch of shorthands like the null-coalesce operator and null-conditional operators. – Christopher Oct 26 '18 at 18:35

4 Answers4

2

Replace:

// WHEN STRING IS MISSING IT BREAKS
try
{
    var answer = prop.GetValue(_typesSheet).ToString();
    answers.Add(answer);
}
catch
{
    continue;
}

With:

var value = prop.GetValue(_typesSheet);
if (null != value)
{
    answers.Add(value.toString());
}
Blue
  • 22,608
  • 7
  • 62
  • 92
HairOfTheDog
  • 2,489
  • 2
  • 29
  • 35
1
if (prop.GetValue(_typesheets) != null) {
    answers.Add(prop.GetValue(_typesheets));
}
emagers
  • 841
  • 7
  • 13
1

The error was caused prop.GetValue(_typesSheet) might be null. when you use ToString method will get

nullreferenceexception

You can try to use linq instead of the foreach.

var answers =
    typeof(TypesSheet).GetProperties()
    .Select(x => x.GetValue(_typesSheet))
    .Where(x=> x!= null)
    .Select(x=> x.ToString());
D-Shih
  • 44,943
  • 6
  • 31
  • 51
1

Use Safe Navigation Operator (available in C# 6)

var answer = prop.GetValue(_typesSheet)?.ToString();
if (!string.IsNullOrEmpty(answer)) answers.Add(answer);

Linq version

var answers = typeof(TypesSheet)
                .GetProperties()
                .Select(prop => prop.GetValue(_typesSheet)?.ToString())
                .Where(answer => !string.IsNullOrEmpty(answer))
                .ToList();