Expressions (C# Programming Guide)
An expression is a fragment of code that can be evaluated to a single value, object, method, or namespace. Expressions can contain a literal value, a method invocation, an operator and its operands, or a simple name. Simple names can be the name of a variable, type member, method parameter, namespace or type.
Expressions can use operators that in turn use other expressions as parameters, or method calls whose parameters are in turn other method calls, so expressions can range from simple to very complex.
The two simplest types of expressions are literals and simple names. A literal is a constant value that has no name. For example, in the following code example, both
"Hello World" are literal values:
For more information on literals, see.
In the example above, both
s are simple names identifying local variables. When those variables are used in an expression, the value of the variable is retrieved and used for the expression. For example, in the following code example, when
DoWork is called, the method receives the value 5 by default and is not able to access the variable
In the following code example, the call to
DoWork is another kind of expression, called an invocation expression.
Specifically, calling a method is a method invocation expression. A method invocation requires the name of the method, either as a name as in the previous example, or as the result of another expression, followed by parenthesis and any method parameters. For more information, see. A delegate invocation uses the name of a delegate and method parameters in parenthesis. For more information, see . Method invocations and delegate invocations evaluate to the return value of the method, if the method returns a value. Methods that return void cannot be used in place of a value in an expression.
Whenever a variable, object property, or object indexer access is identified from an expression, the value of that item is used as the value of the expression. An expression can be placed anywhere in C# where a value or object is required, as long as the expression ultimately evaluates to the required type.