0% found this document useful (0 votes)
71 views6 pages

Variables, Data Types and Operators

The document discusses variables, data types, and operators in C#. It defines variables as storing data in memory and having a name, type, and location. Common data types include primitive types like integers, floats, and booleans. Variables are either value types which store data directly, or reference types which store a memory address. The document also covers naming conventions, constants, keywords, assigning values, and basic operators.

Uploaded by

erza scarlet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
71 views6 pages

Variables, Data Types and Operators

The document discusses variables, data types, and operators in C#. It defines variables as storing data in memory and having a name, type, and location. Common data types include primitive types like integers, floats, and booleans. Variables are either value types which store data directly, or reference types which store a memory address. The document also covers naming conventions, constants, keywords, assigning values, and basic operators.

Uploaded by

erza scarlet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 6

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.

After completing this lesson, you will be able to:


 Compare and contrast the different value data types that are used in C# applications.
 Convert existing variables from one data type to another.
 Use named constants.

Common Type System


A data type is a set of values (how big the object is in memory) and what operations it can do on the
variable or object. C# is a type-safe language; the compiler guarantees that values stored in variables
are always of the appropriate type. It is also a strongly typed language, when a variable is defined or
an object is created, it must have a specific type (int, string or a Student or a Button) that can be used
inside the program.

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.

C# defines two-flavors of variables:


1. Value Types. Value-type directly contains their data and cannot be null; instances of value types
are allocated on the stack or allocated inline in a structure. Value types are mainly primitive
types inherited from System.Value type. It can be built-in (implemented by the runtime), user-
defined or enumeration. Each value-type variable has its own copy of the data, so it’s not
possible for operations on one variable to affect another variable.

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.

Primitive Data Types


Primitive value types are identified by means of reserved keywords. These reserved keywords are aliases
for predefined structure types. A simple type (C# type) and the struct type (.Net type) it aliases are
completely indistinguishable.
C# Size .NET type Description
Type (Bytes)
Byte 1 System.Byte Unsigned 8-bit integer value between 0-255.
char 2 System.Char Unicode characters.
bool 1 System.Boolean True or false.
Sbyte 1 System.SByte Signed byte values between -128 to 127.
short 2 System.Int16 Signed short integer between values -32,768 to 32,767.
ushort 2 System.UInt16 Unsigned short integer values between 0 to 65,535.
int 4 System.Int32 Signed integer values between -2,147,483,648 and
2,147,483,647.
uint 4 System.UInt32 Unsigned integer values between 0 and 4,294,967,295.
float 4 System.Single Single-precision floating point number. Holds the values from
approximately +/-1.5 * 10-45 to +/-3.4 * 1038 with 7
significant figures.
double 8 System.Double Double-precision floating point; holds the values from
approximately +/-5.0 * 10-324 to +/-1.8 * 10308 with 1516
significant figures.
decimal 16 System.Decimal Fixed-precision up to 28 digits and the position of the
decimal point. Typically used in financial calculations.
Requires the suffix "m" or "M."
long 8 System.Int64 Signed integers ranging from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807.
ulong 8 System.UInt64 Unsigned integers ranging from 0 to approximately 1.85 *
1019.

Variables, Constants, and Keywords


Variables
Whenever your application needs to store data temporarily for use during execution, you store that data
in a variable. A variable has three properties: a memory location to store the value, the type of data
stored in the memory location and the names used to refer to the memory location. Variable name is
also referred to as the identifier.

When naming variables, observe naming conventions recommended for C#.


The following are the naming rules for C# variables:
 Start each variable name with a letter or underscore character.
 After the first character, use letters, digits, or the underscore character.
 Do not use reserved keywords.
 Spaces are not allowed.
 Special characters (such as ?,#,!, etc.) are not allowed.

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

Using Primitive Data Types


To create a variable, you must choose a variable name, declare your variable, and assign a value to
your variable. Generally, you declare a local variable using the syntax:
<data type> <variablename1>,[<variablename2>], ........ [<variablenamen>];
Example: int itemCount;
Console.WriteLine("{0}",itemCount); // Compile-time Error! Use of uninitialized variables
Assigning Values to Variables
The assignment operator (=) assigns a new value to a variable that is already declared. For the
assignment to succeed, the value on the right side of the assignment must be a type that can be
implicitly converted to the type of the variable on the left side of the assignment. For example:
int employeeNumber;
employeeNumber = 23;

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.

You can also initialize an enumeration by specifying integer literals.


enum toys {train = 12, dinosaur, excavator = 41, truck };
then toys.dinosaur would have a value of 13 and toys.truck a value of 42.
Example: class Program {
enum Color { red, green ,blue}
static void Main(string[] args){
Color colorpalette1, colorpalette2; // Declare the variables
colorpalette1 = Color.red; // Set the value to red
colorpalette2 = (Color)2; //Typecasting int to Color: blue
Console.WriteLine(colorpalette1); // Display an enumeration value
Console.WriteLine(“{0}”,colorpalette2);
}
}

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.
}

public static void Main(){


Employee companyEmployee; // variable declaration
companyEmployee.firstName = "Joe"; // Set value The syntax to access elements inside the
companyEmployee.age = 23; struct:
variablename.fieldname
Console.WriteLine(companyEmployee.firstName);
Console.WriteLine(companyEmployee.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.

Converting Value Data Types


In C#, there are two types of converting primitive data types:
3. Implicit Data Type Conversion - A value of a narrower data type can be converted to a value of a
broader data type. This implicit conversion is called widening. This conversion always
succeeds, and it never results in a loss of information.
int intValue = 123;
long longValue = intValue; // Implicit conversion of int to long
Console.WriteLine("(long){0}={1}", intValue, longValue);
4. Explicit Data Type Conversion - Converting from a broader data type to a narrower data type is
called narrowing conversion. You can convert variable types explicitly by using a cast
operator or a function (such as Convert.ToInt16(), Convert.ToDouble()).
long longValue = Int64.MaxValue;
int intValue = (int) longValue;
Console.WriteLine("(int) {0} = {1}", longValue, intValue);//(int) 9223372036854775807 = -1

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

You might also like