Variables, Data Types and Operators
Variables, Data Types and Operators
The need to understand how to store and manipulate data in an application is necessary. A variable is
used to store data. When a variable is named, some storage is reserves for that variable by identifying
its data type. After a variable is defined, you can assign values to that variable and operate the data in
it.
The Common Type System (CTS) defines a set of built-in data types that can be used to define variables.
The compilers, tools, and the runtime itself share CTS. CTS is the model that defines the rules that the
runtime follows when declaring, using, and managing types. The types provided by .Net-compliant
generally map to some specific subset (called Common Language Specification (CLS)) of intrinsic types,
that enable cross-language integration, type safety, and high-performance code execution.
2. Reference Types. Reference-type contains reference to the value’s memory address, and is
allocated on the heap. The data for reference-type variables is stored in an instance. Reference
types are derived from Sytem.Object. Reference types can be self-describing types, pointer
types, or interface types. Self-describing types are further split into array and class types. The
class types are user-defined classes, boxed-value types, and delegates. It is possible for two
reference variable to reference the same object, so it is possible for operations on one reference
variable to affect the object referenced by another variable.
It is recommended that you follow these recommendations when naming your variables:
Avoid using all uppercase letters.
Avoid starting with an underscore.
Avoid using abbreviations.
Use descriptive words.
Use the Pascal Casing (capitalize the first character of each word) naming convention for
classes, methods, properties, enums, interfaces, fields, and namespaces.
Example: void InitializeData();
Use the camel casing (capitalize the first character of each word except for the first word )
naming convention, for variables that define fields and parameters.
Example: int loopCountMax;
Constants
A constant is an identifier used in place of a value. Constants should be used for fixed values that occurs
many places in the code. It should also be used in place of a value whose purpose is not immediately
clear from the value. Constants cannot be altered during program execution.
Literal constant is just a value. It does not have a name. For example, 10 is a literal constant.
The value of 10 is always 10. Neither can be assigned a new value to 10 nor represent any other value,
no matter how hard you might try.
Symbolic/Named constant assign a name to a constant value. Use the following syntax to
declare a symbolic constant: const type identifier = value;
Example: const int FreezingPoint = 32;
C# Keywords
Keywords are reserved and have special meanings in C#. Using a keyword as a variable name will result
in a compile-time error. Some C# keywords include the following:
abstract as base bool break byte case catch char
You can also initialize a variable when you declare it. int employeeNumber = 23;
You can use the assignment operator to assign values to variables, like
char middleInitial = 'D';
float vat = 10.5; // careful!, this will lead to loss of precision. cannot implicitly convert double to float
// correct way : float vat = 10.5F;
C# Operators
Expressions are constructed from operands and operators. The operators of an expression indicate
which operations to apply to the operands.
Operator Description Example Result
Arithmetic Assume: A = 10; B=20
+ Adds two operands. A+B 30
- Subtracts second operand from the first. A–B -10
* Multiplies both operands. A*B 200
/ Divides numerator by denominator. B/A 2
% Modulus. Remainder of after an integer B%A 0
division.
Logical Assume: A = true; B = false;
! NOT. Reverses logical state of its operand. !A false
&& Conditional AND. If both the operands are A && B False
non-zero then condition becomes true.
|| Conditional OR. If any of the two operands is A || B True
non-zero then condition becomes true.
Increment and Decrement Assume: A = 10
++ Increments operand by 1. A++; ++A 11
-- Decrements operand by 1. A--; --A 9
Comparison Assume: A = 10; B = 20
== Equality. (A == B) False
!= Inequality. (A != B) True
< Less than. (A < B) True
> Greater than. (A > B) False
<= Less than or equal. (A <= B) True
>= Greater than or equal. (A >= B) False
Bitwise Assume: A = 60; B = 13
& Bitwise AND. Copies a bit to the result if it (A & B) 12
exists in both operands. 000011002
| Bitwise OR. Copies a bit to the result if it (A | B) 61
exists in either operand. 001111012
^ Bitwise Exclusive OR. Copies the bit to the (A ^ B) 49
result if it is set in one operand but not both. 001100012
~ Bitwise complement; has the effect of (~A) 61
“flipping” of bits. 110000112
>> Right Shift. The left operands value is moved (A >> 2) 15
right by the number of bits specified by the 000011112
right operand.
<< Left Shift. The left operands value is moved (A <<2) 240
left by the number of bits specified by the 111100002
right operand.
Assignment Assume A=10; B= 20; C= 30
= Assigns the value of the right operand to the C=A+B 30
left operand.
+= Addition assignment. C += A 40
-= Subtraction assignment. C -= A 20
*= Multiplication assignment. C *= A 300
/= Division assignment. C /= A 3
%= Modulus assignment. C %= A 0
&= AND assignment. C &= A 10
|= OR assignment. C|= A 30
^= Exclusive OR assignment. C ^= A 20
Object Creation
new Creates an instance of an object. Student student = new
Student();
Member Access
. (dot) Used to access members of a type. student.Name =””;
Casting
() Explicit Conversion (int)11.7 11
as Conversion between compatible reference Student s = pupil as
types without raising an exception if fails. Student();
Indexing
[] Array indexing. Also used to specify temperature[4]=12.5;
attributes.
Conditional
?: Ternary operator. result=(10<20)?1:2; 1
Type Information
is Type comparison. Check if an object is of the if(Suzuki is Car)
class type
sizeof() Returns the size, in bytes, of a value type. sizeof(int) 4
typeof() Returns the type of an object as a typeof(StreamReader);
System.Type object
Hint. The conditional AND and OR operators (&& and ||) perform short-circuit evaluation. This means that they
do not evaluate the second part of an expression if there is no need to. There is some performance benefit to not
having to look at the second operand. Be cautious when you are using short-circuit evaluation to make sure that you
aren't introducing an unexpected side effect by not evaluating an operand.
Operator Precedence
Precedence is the order which a series of operators are evaluated.
Order Category Operators Associativity
1. Highest Primary (x) x.y f(x) a[x] x++ x-- new typeof checked Left
unchecked
2. Unary + - ! ~ ++x --x (T)x sizeof Right
3. Multiplicative */% Left
4. Additive +- Left
5. Shift << >> Left
6. Relational and < > <= >= is, as Left
type testing
7. Equality == != Left
8. Bitwise AND & Left
9. Bitwise XOR ^ Left
10. Bitwise OR | Left
11. Logical AND && Left
12. Logical OR || Left
13. Conditional ?: Right
14. Lowest Assignment = *= /= %= += -= <<= >>= &= ^= |= Right
Rules in Evaluating Expressions.
1. Parentheses Rule. What is inside the innermost parentheses must be evaluated first and the next
innermost and so on. For example: (a/b - (c + (d - e) * f)), first subtract e from d and then multiplies
the result to f, then adds it to c, then divide a from b, then subtract. Parentheses controls precedence
and associativity.
2. Operator Precedence Rule. Refer to the table of operators and its order of precedence.
3. Associativity Rule. The associativity controls the order in which the operators are performed
when an expression contains the same operator many times or an expression has operators of equal
precedence.
Creating User-Defined Data Types
User-defined types can be used in the same way as primitive ones. The only real difference between
primitive data types and user-defined data types is that you can write literal values for the primitive
types.
Enumeration Types
Enumerations provide a powerful alternative to literal or simple symbolic constants. An enumeration is
a distinct value type, consisting of a set of named constants (called the enumerator values). The
syntax to declare an enumeration: enum enumeration_name { enumerator_values }
Example: enum Color { Red, Green, Blue } // defines three integer constants
By default, enumerator values start from 0. In the preceding example, Red has a value of 0, Green
has a value of 1, and Blue has a value of 2.
Structure Types
Structures group together several arbitrary types. It can be used to create objects that behave like built-
in value types. structs are stored inline and are not heap allocated so there is less garbage collection
pressure on the system than there is with classes.
public struct Employee{
public string firstName; This code defines a new type called Employee that consists of two
public int age; elements/fields: firstName and age.
}
Variables of the struct type are value types. This means that when you declare a struct variable (such
as companyEmployee in Main), you create a value on the stack. The declaration of companyEmployee
creates companyEmployee.firstName and companyEmployee.age on the stack. These two fields are
not, default initialized to zero or empty string. Hence the value of companyEmployee.firstName or
companyEmployee.age cannot be read until they have been assigned a definite value.
Values are scoped to the block in which they are declared. In this example, companyEmployee is scoped
to Main. This means that when the control flow exits Main (either through a normal return or because
an exception has been thrown), companyEmployee will go out of scope; it will cease to exist.
The code displays a wrong value for the variable intValue -- -1. When you use the cast operator, you
should be aware that problems (such as trying to fit the value 9223372036854775807 into an int variable)
might occur if the value cannot be held in the target variable. To avoid such a situation, use the checked
statement to raise an OverflowException when an explicit conversion fails. If you want, you can catch
this exception by using try and catch, as shown.
try{
checked{
long longValue = Int64.MaxValue;
int intValue = (int) longValue;
Console.WriteLine("(int) {0} = {1}", longValue,intValue);
}
}
catch { // using general exception
Console.WriteLine("Problem in cast");
References:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/
www.articles.com
www.akadia.com
www.blackwasp.co.uk
www.bogotobogo.com
www.c-sharpcorner.com
www.codeproject.com
www.completechsarptutorial.com
www.csharp-sation.com
www.chsarp.net-tutorials.com
www.develop.com
www.geom.ulcc.edu
www.Indiabix.com
www.tutorialspoint.com
www.w3schools.com