Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement


Full article

This error might look a little cryptic at first glance, but it's actually very descriptive in explaining what's wrong. You're likely to come across this one when you're starting out with C# ... or before your first cup of coffee. ๐Ÿ˜

What does it mean?

Basically, it's telling you that what you typed isn't a valid statement. Which begs the question, what is a statement? Well, it's every valid line (or in some cases, block) of code that makes up your program, for example:

  • Assignments: string name = "Grant";
  • Calls: MyOtherFunction();
  • Increments: x++;
  • Decrements: x--;
  • Await: await myLongTask;
  • New object expressions: new Person();

In general, most statements should either modify a variable's value in-place, perform some side-effect (like a foreach block), or at least do something with the return value.

So if you get this error, double-check the line it's complaining about to make sure it's a valid statement, specifically one of the types listed in the error message itself.

What should you check for?

  • Are you missing a set of parentheses?
  • Did you use == instead of =?
    string name;
    name == Grant;
  • Did you combine elements of a property and method?
    public string Name() { get; set; }
  • Does your statement only return a value, but you're doing nothing with it?
    var hi = "Hello, "; hi + " Grant";

If none of those do it for you, feel free to leave a comment below. Heck, post the offending line, and we'll debug it together - and maybe I'll have something else to add to this list!


Grant Winney

I write when I've got something to share - a personal project, a solution to a difficult problem, or just an idea. We learn by doing and sharing. We've all got something to contribute.

Comments / Reactions

One of the most enjoyable things about blogging is engaging with and learning from others. Leave a comment below with your questions, comments, or ideas. Let's start a conversation!