In this page:
- Assign values to variables and constants
- Assignment relevant questions
Assign values to variables and constants
In the last post I mentioned variables and constants in C#, variable stores a value of which data is subject to change during the program running, constant stores a value whose data is not able to change during its lifecycle. I also mentioned before you can use the variables or constants, you must give them initial values. Today I am talking about how to assign values to variables and constants.
In C#, an assignment operator (=) can evaluate the value of the right side operand and then assign it to the left side variable (because constant is a special type of variable, I will use variable to refer both invariant and variant data). Assignment operator is binary, which means this operator has to take two operands to work. The typical usage of the assignment operator is like this:
[type] <variable-name> <=> <expression> [, <variable-name2> <=> <expression2> [, …]] <;>
Let me explain the signs I used to describe the syntax:
- [ ]: Indicates the terms appear in the parentheses body are optional.
- < >: Indicates the terms appear in the parentheses body are required.
- …: Indicates the terms before the ellipsis can appear one or more times.
The symbolic syntax above can define a variable with a specific type and an initial value. For example,
defines an integer variable with initial value 1.
Note, please pay attention to the distinctions between definition and declaration. When we declare a variable, we just tells the compiler the name and the type of that variable; when we define a variable, the name, the type and the initial value are given to the compiler. I see some abuse of these two terms in a lot of books, although sometimes we really don’t care which term we are using, but I still want to clarify the difference. Please make it in your mind.
Except define an integer variable, you can assign different variables with different types and values. For example:
- int intValue = 1;
- uint unsignedIntValue = 2;
- long longValue = -32767;
- ulong unsignedLongValue = 65536;
- double doubleValue = 1e+15;
- decimal decimalValue = 10000000000000000000;
These variables are numbers. Different numeric types have different value boundaries. for a complete list of numeric types and its value ranges, please see this link.
I may go deep into those types when I refer to C# type system in the further posts.
You may also define more than one variables in a same line of code, use a comma to separate each definitions. For example:
- string s1 = "My", s2 = "New", s3 = "HDTV";
- int i, j = 0, k = 1, l;
In this example, I defined 3 string variables, “My”, “New” and “HDTV” in a same line; in the second line, I defined 4 integer variables, i, j and l is 0, k is 1.
Note, you cannot assign different types of variable in a same line, for example, this line will lead a compiler error:
- string s = "Hello", int i = 1;
If you really want to do so, change the comma sign to a semi-comma to resolve the compiler error:
- string s = "Hello"; int i = 1;
A semi-comma differentiates two C# statements, the compiler will treat the above line as two independent statements, the following code is equivalent to the above:
- string s = "Hello";
- int i = 1;
Furthermore, you can assign values in a same line as a chain, for example:
We can also decouple declaration from definition, for example:
- int i;
- string s;
-
- i = 1;
- s = "Hello";
To assign a value to a constant, put a const keyword before the type of the variable. For example:
- const double pi = 3.1415926;
- const string httpPrefix = "http://";
-
- double area = 2 * 2 * pi;
- string url = httpPrefix + "www.markzhou.com";
As I aforementioned, constants are compiled to its actual value (literal) to optimize the executable.
Assignment relevant questions
Q1: Can I assign a return value from a method to a constant?
A: No. Constant must be assigned with a constant expression, that is, an expression that consists of constants, or predefined values from the system, and (if applied) the operations on these types (such as addition, subtraction, multiplication, division, increment, decrement, bit-and, bit-or, bit-not, logical/conditional operations etc.).
Q2: Does this code compile?
- string s1, s2, s3 = "Hello";
- object o1, o2 = new object { };
A: Yes. Compiler will treat s1, s2 as declarations, s3 as definition. The same mechanism applies to the second line. But please be aware, the following code has no declaration. Because the compiler will automatically add a default value to int types (will introduce later):
The above line is equivalent to:
- int i = default(int), j = default(int), k = default(int);
Also equivalent to:
Q3: Can I assign a string value to an int variable?
A: No. C# is restricted as a strong typed programming language. You cannot assign a different value to a type that is not compatible. For example, you may assign a long integer to an int variable because it is implicitly convertible from long to int, but you cannot assign a int value to a string. The only way to do this is using conversions (will introduce later).
Q4: Does C# return a value from an assignment? is that value right-evaluated?
A: C# returns a value for a assignment statement, however, unlike the C programming language, C# does not returns the value of the right operands of an assignment statement. For example:
- class A { }
- class B : A { }
- class C : B { }
-
- class Program
- {
- static void Main(string[] args)
- {
- A a = new A();
- B b = new B();
- C c = new C();
-
- Console.WriteLine((b = c).GetType()); // Demo.C
- Console.WriteLine((a = b = c).GetType()); // Demo.C
- }
- }
The first output is “Demo.C”, expression “b = c” return a type of Demo.C, the right value is of type Demo.C, the left value is of type Demo.B; The second output is “Demo.C”, expression “a = b = c” returns a value of type Demo.C, but a, b, c is of type Demo.A, Demo.B and Demo.C. As you can see, C# doesn’t evaluate the value of an assignment expression strictly from the left or right. C# always evaluates assignment expression by its calculated underlying value.