You are on page 1of 54

University of Computer Studies

Chapter (1)
Basic Concepts

1
Contents
 Data Types
 Default Values
 Variable
 Naming Variable
 Variable Declaration
 Constant Variable
 Keywords
 Literals
 Escape Character
 Comments

2
Contents
 Data Type Conversion

 Implicit Conversion

 Explicit Conversion

 Scope

 Nullable Type

 Enumeration

 Array

 One-Dimensional Array

 Multi- Dimensional Array

 Jagged Array

3
Data Types
 All types ultimately inherit from object.
 The smallest piece of data that a computer can handle is a bit, a single value that can be either 0 or 1.
 Eight bits are grouped in a byte.

4
Cont’d
Name  Type  Size 

Boolean  bool  1 bytes 


Byte  byte  1 bytes 
Singed byte  sbyte  1 bytes 
Character  char  2 bytes 
Short integer  short  2 bytes 
Unsigned short integer  ushort  2 bytes 

Integer  int  4 bytes 


Unsigned integer  uint  4 bytes 
Long integer  long  8 bytes 
Unsigned long integer  ulong  8 bytes 

5
Cont’d
Decimal  decimal  16 bytes 

Single-precision floating point float  4 bytes 


number 
Double-precision floating point double  8 bytes 
number 
String  string  varies 

Date and Time  DateTime  8 bytes 

Object  object  4 bytes 

Class  class  varies 

Structure  struct  varies 

6
Cont’d
C# Data Types

Value Data Types Pointer Reference Data Types

User-defined Types Predefined Types User-defined Types


     Predefined
   Types

bool
byte
ubyte
char
short Object
ushort enum class
int string interfaces
struct
uint delegates
long
ulong
decimal
float
double
DateTime 7
Cont’d

        

8
Stack and Heap
 Stack is used for static memory allocation.
 Heap is used for dynamic memory allocation.
 It is stored in the computer's RAM.
 It is stored in the computer's RAM.
 Use the stack if you know exactly how much data
 Use heap if you don't know exactly how much data
you need to allocate before compile time and it is not
too big. you will need at runtime or if you need to allocate a
 It is LIFO data structure. lot of data.
 It is stored Directly.  Chunks are allocated to store certain kinds of data
 Variables can’t be resized. objects.
 Its access fast.  Data can be stored and removed in any order.
 It contains values for Integral Types, Primitive Types  It is stored indirectly.
and References to the Objects
 Variables can be resized.
 Its access is slow.

9
Stack and Heap

10
Data Types: Value Type
 A value type is a simple data type such as int or float that represents the data directly.

 Fixed length

 Store on the stack

 Predefined value types : Numeric types, Boolean types and Character types

 User-defined value types : struct and enumerations

 A new type : nullable type

 this type variable can hold an undefined value

 any value type variable can be defined as a nullable type

                                         11
Data Types: Value Type
                                        
Example:     int num = 100;
int x=10;
int y = x;
num

x 10

                                 
value copied

RAM
y 10

12
Data Types: Reference Type
 A reference type contains a reference to another piece of memory that  actually contains the variable’s data.  

 String, all Arrays, Class, Interface, Delegates are reference type.

 Variable length

 Store on the heap

        

13
Data Types: Reference Type
 User-defined type ( or complex type)

              Classes,
               Interface,
                  Delegates
                   and
       Arrays
          
 Predefined ( or simple ) types
Object type and String type
                           Circle c = new Circle( )

                         
object

         c

Stack Heap

14
Data Types: Reference Type
 When an assignment between two reference variables occurs, only the reference is copied
 The actual value remains in the same memory location (i.e. there are two references to a single value)

                                                                                      
p1 0x332255
Person p1 = new Person( ); 0x332255
p1.name = “Su Su”;
            Person
               p2
   =
      p1;
       Reference
copied Su Su

                         
p2 0x332255

        
Stack Heap
15
Default Value
Type  Default Value 

All Integer Types  0 

char type  ‘\x000’ 

float type  0.0f 

double type  0.0d 

decimal type  0.0m 

bool type  false 

enum type  0  

All reference type  null 


16
Variable
 A variable is a name given to storage area that is used to store a value of various data types.

 It is a box in the computer’s memory holding temporary information.

 Each variable in C# have a specific type.

 A variable is either explicitly assigned a value or automatically assigned a default value.

17
Naming Variable
 It should begin a letter (A-Z, a-z), underscore, or @ symbol. 
 After that it can include letters (A-Z, a-z), numbers (0-9), or underscore.
 If the name begins with @, it must include at least one other character.
 It cannot contain special characters such as &, %, #, and $. 
 It cannot be the same as C# keywords such as if, for, and public, etc.

 num1 - valid                               
 Num1 - valid
 student_Name - valid                     
 class              - invalid                   
 student Name - invalid
 #studentName - invalid
 return - invalid
 1num  - invalid
18
Variable Declaration 

 int num; // declare num variable with “int” data type

 int amount = 30000; // declare int type variable named “amount” with initialization

 double[]  salary; // declare salary variable with double array type

 string[,]  student; // declare student variable with two dimensions string array type 

 const double pi = 3.14 // declare constant variable pi with double type. Its value cannot be changed later.

19
Constant Variable

 A variable whose value will not change during the lifetime of the program.

 A constant variable must be initialized at its declaration.


 “const” keyword is used to declare constant variable.
 Constant variable is stored on stack.
 Constant is used to create a variable which value can not be changed.
 Value of constant must be computable at compile time.

20
Nullable Type
 A null value indicates that a field does not contain any data.
 A value type cannot be assigned a null value. 
 For example, int i = null will give you a compile time error.
 C# introduced nullable types that allow you to assign null to value type variables. 
 Nullable types can only be used with value types.

Example
int?  i = null;
double?   num = null;
num = 4.5;

21
Keywords
abstract  as  base  bool  break 
byte  case  catch  char  checked 
class  const  continue  decimal  default 
delegate  do  double  else  enum 
event  explicit  extern  false  finally 
fixed   float  for   foreach  get 
goto  if  implicit  in   int 
interface  internal  is  lock  long 
namespace  new  null  object  operator 
out  override  params  private  protected 
public  readonly  ref  return  sbyte 
sealed  set  short  sizeof  stackable 
static  string  struct  switch  this 
throw  true  try  typeof  unit 
ulong  unchecked  unsafe  unshort  using 
virtual  void  while     
22
Literals

23
Literal: Integer Literal
 A literal of integer type is know as the integer literal.

 It is used to write values of types int, uint, long, and ulong.

 It can be octal, decimal, binary, or hexadecimal constant.

 A prefix specifies the base.

 No prefix is required for the decimal numbers.

 A suffix can also be used with the integer literals like U or u are used for unsigned numbers while l or L are used for long
numbers.
Example
20 // int
30u // unsigned int
30l // long
0x4b // hexadecimal 24
Literal: Literal Type Character

Character  Data Type 

U  uint 

L  long 

UL, LU  ulong 

F  float 

D  double 

M  decimal 

25
Literal: Real Literal

 Real literals are used to write values of types float, double, and decimal.

 one or more digits containing a decimal point (the decimal point can appear before, within, or after the digits),

 optionally preceded by a sign (+ or -),

 optionally followed by an exponent letter and exponent,

 optionally followed by kind type parameter.

Example

float ff = -12.55f;

double dd = 2.5e-5D;

decimal mm = 1234e5M;

26
Literal: Boolean Literal

 only two Boolean literals: true and false

Example:

bool flag = false;

27
Literal: Single Character Literals &
String Literals
 ‘2’ ( Single character literals )

 “2000019” ( String literals )

Example:

char grade=‘A’;

string result=“Credit”;

28
Escape Character
Escape Character  Meaning 
\a  alert 
\b  backspace 
\f  form feed 
\n  new line 
\r  carriage return 
\t  horizontal tab 
\v  vertical tab 
\’  single quote 
\”  double quote 
\\  backslash 
\0  null 
29
Comments

1. Single line comments


        int num = 10;    // variable declaration

2.     Multi-line comments


            /* The following is a multi-line
                     Comment in C#  */

30
Data Type Conversion

 It happens when the value of one data type is assigned to another data type. 

If the data types are compatible, C# does automatic Type Conversion (Implicit

Conversion).

If not compatible, need to be converted explicitly which is known as Explicit

Type conversion.

31
Implicit Conversion

 narrowing conversion: change a value to a data type that might not be able to hold this value
Example: long salary = 300000;
int empSalary = salary;

 widening conversion: change a value to a data type that can hold this value.
Example: float m = 80.5;
double mark = m;
32
Explicit Conversion
 These are done explicitly by users using the pre-defined function.  
 It requires a cast operator. 

Casting 
 A cast operator explicitly tells a program to convert a value from one type to another type. 
Example: long  salary = 300000; 
int   empSalary = (int) salary; 

Casting Array
 double[]     num = new double[10];
 float[]        mark =(float[]) num;

 long[]   salary = new long[20];


 int[ ]     S = (int[]) salary;
33
Explicit Conversion

Parsing
 To convert a string into other data types
Example:
string num= “1234567”;
int value = int.Parse ( num );

 int.Parse(), long.Parse(), double.Parse(), float.Parse(), decimal.Parse(), bool.Parse(), DateTime.Parse(),etc…

Using System.Convert
 Convert class has a variety of methods that values from one type to another.

34
Explicit Conversion

No  Method  Description 

1  ToBoolean  Convert a type to a Boolean value, where possible 

2  ToByte  Convert a type to a byte 

3  ToChar  Convert a type to a single Unicode character, where possible 

4  ToDateTime  Convert a type (integer or string type) to date-time structures 

5  ToDecimal  Convert a floating point or integer type to a decimal type 

6  ToDouble  Convert a type to a double type 

7  ToInt16  Convert a type to a 16 bit integer 

8  ToInt32  Convert a type to a 32 bit integer 

35
Explicit Conversion

No  Method  Description 

9  ToInt64  Convert a type to a 64 bit integer 

10  ToSbyte  Convert a type to a singed byte type 

11  ToSingle  Convert a type to a small floating point number 

12  ToString  Convert a type to a string 

13  ToType  Convert a type to a specified type 

14  ToUInt16  Convert a type to an unsigned int type 

15  ToUInt32  Convert a type to an unsigned long type 

16  ToUInt64  Convert a type to an unsigned big integer 

36
Scope

 A variable’s scope determines which other pieces of code can access it. 
 If a variable is declared inside a method, only code within that method can access the variable.

Block Level Scope
 Block is a series of statements enclosed in braces. 
 If a variable is declared within a block of code, the variable has block
scope, and only other code within that block can access this variable.

37
Scope
Example:                
   int i=0; else
       {   int product = i * j;
            for (i = 0; i < 10; i++)            Console.WriteLine("Product = " + product);
            {          }
                int j = 5;
                int k  = 100;
                if (i == j)                 Console.WriteLine("K = " + k);
                {
    }
                    int sum = i + j;
                Console.WriteLine("Sum = " + sum);
                }

38
Scope
Method Scope
 If a variable is declared inside a method but not within a block, the variable is visible to any code inside the method that follows
the declaration.
Example: 
                 int Sum (int num1,int num2)
                {      int sum = num1 + num2;           
                         return sum;   
         }

Class Scope
 A variable with class or structure scope is available to all code in this class or structure even if the code appears before this
variable’s declaration.

39
Scope
Example:
class Circle
     {
          public double CalArea( )
          {
              area = Math.PI * 4.5 * 4.5;
              return area;
          }
            double area;
       }

40
Enumeration

 An enumeration called “enum” is a discrete list of specific values called enumerators.

 To define a constant set of values.

 C# enumerations are value data type. 

 Enumeration contains its own values.

 An enumerated type is declared using “enum” keyword.

 By default, the first member of an enum has the value 0 and the value of each successive enum member is increased by 1.

 By default, an enumeration’s type is int.

41
Enumeration

Enum Variable Declaration


        enum  enum_name  { enumeration list  }

42
Enumeration
Example

enum  Days { Sun, Mon, Tue, Web, Thu, Fri, Sat };


Days     d; // declaration variable “d” with enum “Days” type
int dayNumber = (int) Days.Tue;

enum Days enum Meal  : sbyte


{   {
Sun = 3,         Breakfast = 1,
Mon,         Lunch = Breakfast * 10,
Tue,        Dinner = 300,
Wed,        Supper
Thu,  Fri,   Sat   }
}
43
Arrays

 An array is a special data type which can store fixed number of values sequentially in the memory.
 Data type of all values in array must be the same.
 Array in C# is a reference type which is derived from System.Array class.
 Copying an array variable copies the reference only

10  200  30  500  45  33  23  80 

0  1  2  3  4  5  6  7 

     Lower bound Index                                                                                       Upper bound Index 


                              
Value Array Representation 44
One-Dimensional Array
Example: Array Declaration 
int[] mark;    // to store int value
bool[] B; // to store boolean value
double[ ] D; // to store double value

Example: Array Declaration and Initialization

int[ ] arr = new  int[5] ;


(or)
int[ ] arr = {10,20,30,40,50} ;

45
One-Dimensional Array
string[]  name = new string[3]{“Su Su”, “Yu Yu”, “Aung Aung”};
long[] salary = {400000L, 5000000L,200000L};
string[] color;
color = new string[3] {“White”, “Orange”, “Red”};

Example: Assigning Array
string[] color = new string[3];
color[0] = “White”;
color[1] = “Orange”;
color[2] = “Red”;

Example: Accessing Array Element


color[1]; // returns “Orange”

46
One-Dimensional Array
Example: Displaying Array Element
string[]  name = new string[3]{“Su Su”, “Yu Yu”, “Aung Aung”};
for(int i=0; i< name.Length; i++)
{ Console.WriteLine(name[i]); }
           (or)
foreach( string st  in name)
{ Console.WriteLine(st)); }

Example: Sorting and Reversing Array Element


long[] salary = {400000, 5000000,200000};
Array.Sort(salary);
Array.Reverse(salary);

47
Array Properties and Methods

Method/ Property Name  Description 

GetLength (int dimension)  Returns the number of elements in the specified dimension 

GetLowerBound(int dimension)  Returns the lowest index of the specified dimension 

GetUpperBound(int dimension)  Returns the highest index of the specified dimension 

GetValue(int index)  Returns the value at the specified index 

Length  Returns the total number of elements in the array 

48
Multi-Dimensional Array
 A multi-dimensional array is a two dimensional series like rows and columns.
    Example: 
                    int[,] num = new int[  3    ,     3   ]

                                         No of Rows     No of Columns

double[,]  salary;
int[,]  num = new int[3,2] { { 10,11}, { 20,3}, {2, 55}};

int[,]  point=  { { 10,11}, { 20,3}, {2, 55} };


point[1,0];

49
Multi-Dimensional Array

string[ , ] subject = {
{ “C#”, “JAVA”, “C++”},
{ “C”, “VB.NET”, “C#.NET”},
{ “XML”, “HTML”, “SQL”},
};

for (int i = 0; i < subject.GetLength(0); i++)


{
for (int j = 0; j < subject.GetLength(1); j++)
{
Console.Write(subject[i, j] + " ");
}
Console.WriteLine();
}

50
Jagged Array
 A jagged array is an array of an array. 
 It stores arrays instead of any other data type value directly.
 A jagged array is initialized with two square brackets [][].
 The first bracket specifies the size of an array and the second bracket specifies the dimension of the array which is
going to store as values.

type [][] array_name = new type[size][dimension of array];

A
Example
int[][]   A  = new int[2][ ]; 
1 2 3
A[0] = new int[3]{1, 2, 3};  0

A[1] = new int[2]{4, 5 }; 


1 4 5
51
Jagged Array

int[][] A= new int[3][]
                        {
                            new int[3]{15, 7, 22},
                            new int[2]{67, 81},
new int[4]{12,91,1,17}
                        };
Console.WriteLine(A[0][0]); 
Console.WriteLine(A[1][1]);      
Console.WriteLine(A[2][3]); 

52
Jagged Array

1 2
int[][,] B = new int[3][,];
B 3 4
B[0] = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; 0 5 6

B[1] = new int[2, 2] { { 3, 4 }, { 5, 6 } }; 


1 3 4
B[2] = new int[2, 2]; 5 6
2

0 0
0 0

53
Thank You

54

You might also like