Skip to content

Instantly share code, notes, and snippets.

@idusortus
Last active April 9, 2021 14:25
Show Gist options
  • Save idusortus/f70589419ec8d5fe66742ae81d3a3a79 to your computer and use it in GitHub Desktop.
Save idusortus/f70589419ec8d5fe66742ae81d3a3a79 to your computer and use it in GitHub Desktop.
C# - Expressions vs. Statements

Statements

From Microsoft:
The actions that a program takes are expressed in statements.

  • Do not return a value
  • Cannot be chained
  • May contain expressions
  • Generally cannot be used as expressions

Expressions

From Microsoft:
"An expression is either a non_assignment_expression or an assignment."

"An expression is a sequence of one or more operands and zero or more operators that can be evaluated to a single value, object, method, or namespace"

  • Resolves to a value
  • Constructed from operators and operands
  • Can be chained / combined to form other expressions
  • Can be used as a statement

Statements

// Declaration statements
string message;
double cashInBank;
System.Text.StringBuilder sb;

// Assignment statements
message = "QWERTYUIOP";
cashInBank = 42.42;

// A declaration statement with an initializer can be viewed as
// a declaration statement followed by an assignment statement
int age = 42;
List<string> names = { "Samuel", "Bryce", "Conrad" };

// Selection statements contain (if, switch)
// Iteration statements contain (while, do, for, foreach)
// Jump statements contain (break, continue, goto, throw, return, yield)
// Other statements contain ( [try...catch], [try...finally], checked, unchecked, lock, using)

// Statement lambda
(input-params) => { <sequence-of-statements> };

Expressions

// by no means is this an exhaustive list

age = 44;                    // assignment expressions              
--age;                       // Decrement expression
new Foo();                   // Object instantiation expression
Foo.DoSomethingUseful(bar);  // Method call expression
y = MyHelpers.Add(1,1);      // Assignment expression

// Expression lambda
(input-params) => expression;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment