1

I am new to C# and I'm trying to write a contains statement. I want the process to read the test variable and if it contains the word error then print the variable if it does not contain an error then print no error. I think my process is close except when I run the code below I get an error when the CLI runs.

"object reference not set to an instance of an object"

Any help would be appreciated!

        while (true)
        {
            test = queue.GetMessage();
            if (test.AsString.Contains("error"))
            {
                Console.WriteLine(string.Format("Variable: {0}", test.AsString));

            }
            else
                Console.WriteLine(string.Format("No Error: {0}", test.AsString));
        }
ssilas777
  • 9,672
  • 4
  • 45
  • 68
AAA
  • 2,388
  • 9
  • 32
  • 47

2 Answers2

2
var message = queue.GetMessage()?? string.Empty;
var formattedMessage =
            String.Format(
                (message.IndexOf("error", StringComparison.OrdinalIgnoreCase) >= 0)
                    ? "No Error: {0}"
                    : "Variable: {0}", message);
Console.WriteLine(formattedMessage);

Useful references:

  1. Unique ways to use the Null Coalescing operator
  2. Simplify conditional string format
Community
  • 1
  • 1
Carbine
  • 7,849
  • 4
  • 30
  • 54
1

If queue.GetMessage() return a string, then you don't need AsString. If you want to convert it to a string, override ToString().

while (true) {
    test = queue.GetMessage();
    if (test.ToString().Contains("error")) {
        ...
    } else { 
        ...
    }
}

You can always guarantee that ToString() will be present because it's defined in the object base class. Just be sure it returns something intelligible, because default implementations may not.

James Cronen
  • 5,715
  • 2
  • 32
  • 52