UNIT II
C# Languages Basics , Data Types , Type Conversion , Boxing & Unboxing ,
Conditional Statements , Looping , Methods in C# , Properties, Arrays , Indexes,
Structures, Enumerations , Strings, Regular Expressions , Collections
C# Languages Basics:
A C# program consists of the following parts:
Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements and Expressions
Comments
Important points
C# is case sensitive.
All statements and expression must end with a semicolon (;).
The program execution starts at the Main method.
Unlike Java, program file name could be different from the class name.
Example program
using System;
namespace HelloWorldApplication
{
Class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
The first line of the program using System; - the using keyword is used to include the System
namespace in the program. A program generally has multiple using statements.
The next line has the namespace declaration. A namespace is a collection of classes. The
HelloWorldApplication namespace contains the class HelloWorld.
The next line has a class declaration, the class HelloWorld contains the data and method
definitions that your program uses. Classes generally contain multiple methods. Methods define
the behavior of the class. However, the HelloWorldclass has only one method Main.
The next line defines the Main method, which is the entry point for all C# programs. TheMain
method states what the class does when executed.
The next line /*...*/ is ignored by the compiler and it is put to add commentsin the program.
The Main method specifies its behavior with the statement Console.WriteLine("Hello
World");
WriteLine is a method of the Console class defined in the System namespace. This statement
causes the message "Hello, World!" to be displayed on the screen.
The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a
key press and it prevents the screen from running and closing quickly when the program is
launched from Visual Studio .NET.
Data Types:
The varibles in C#, are categorized into the following types:
Value types
Reference types
Pointer types
Value Type
Value type variables can be assigned a value directly. They are derived from the class
System.ValueType.The value types directly contain data. Some examples are int, char, and
float, which storesnumbers, alphabets, and floating point numbers, respectively. When you
declare an int type, thesystem allocates memory to store the value.
Reference Type
The reference types do not contain the actual data stored in a variable, but they contain a
reference to the variables.In other words, they refer to a memory location. Using multiple
variables, the reference types canrefer to a memory location. If the data in the memory location is
changed by one of the variables,the other variable automatically reflects this change in value.
Example of built-in reference types are: object, dynamic, and string.
Object Type
The Object Type is the ultimate base class for all data types in C# Common Type
System CTS.Object is an alias for System.Object class. The object types can be assigned values
of any other types, value types, reference types, predefined or user-defined types. However,
before assigning values, it needs type conversion. When a value type is converted to object type,
it is called boxing and on the other hand, when anobject type is converted to a value type, it is
called unboxing.
object obj;
obj = 100;
Dynamic Type
You can store any type of value in the dynamic data type variable. Type checking for
these types of variables takes place at run-time. Dynamic types are similar to object types except
that type checking for object type variables takes place at compile time, whereas that for the
dynamic type variables takes place at run time.
Syntax for declaring a dynamic type is:
dynam ic <variable_nam e> = value;
For example,
dynam ic d = 20;
String Type
The String Type allows you to assign any string values to a variable. The string type is
an alias for the System.String class. It is derived from object type. The value for a string type can
be assigned using string literals in two forms: quoted and @quoted.
For example,
String str = "Tutorials Point";
A @quoted string literal looks as follows:
@ "Tutorials Point";
Pointer Type
Pointer type variables store the memory address of another type. Pointers in C# have the
same capabilities as the pointers in C or C++.
Syntax for declaring a pointer type is:
type* identifier;
For example,
char* cptr;
int* iptr;
Type conversion:
Type conversion is converting one type of data to another type. It is also known as Type
Casting. In C#, type casting has two forms:
Implicit type conversion - These conversions are performed by C# in a type-safe manner.
For example, are conversions from smaller to larger integral types and conversions from
derived classes to base classes.
Predefined implicit type conversation methods are given below
1 . ToBoolean ------Converts a type to a Boolean value, where possible.
2 . ToByte -----Converts a type to a byte.
3 . ToChar -----Converts a type to a single Unicode character, where possible.
4 . ToDateTime ---Converts a type integerorstringtype to date-time structures.
5 . ToDecimal ----Converts a floating point or integer type to a decimal type.
6 . ToDouble -----Converts a type to a double type.
7 . ToInt16 -----Converts a type to a 16-bit integer.
8 . ToInt32----Converts a type to a 32-bit integer.
9 . ToInt64----Converts a type to a 64-bit integer.
10 . ToSbyte--Converts a type to a signed byte type.
11 . ToSingle---Converts a type to a small floating point number.
12 . ToString---Converts a type to a string.
13 . ToType---Converts a type to a specified type.
14. ToUInt16---Converts a type to an unsigned int type.
15. ToUInt32---Converts a type to an unsigned long type.
16. ToUInt64---Converts a type to an unsigned big integer.
Eg:
using System ;
nam espace TypeConversionApplication
{
class StringConversion
{
static void Main(string[] args)
{
int i = 75;
float f = 53.005f;
double d = 2345.7652;
bool b = true;
Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
Console.ReadKey();
}
}
}
o/p:
75
53.005
2345.7652
True
Explicit type conversion - These conversions are done explicitly by users using the predefined
functions. Explicit conversions require a cast operator.
Eg:
using System ;
nam espace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
double d = 5673.74;
int i;
i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}
Boxing and Unboxing:
Boxing
Implicit conversion of a value type (int, char etc.) to a reference type (object), is known
as Boxing. In boxing process, a value type is being allocated on the heap rather than the stack.
Unboxing
Explicit conversion of same reference type (which is being created by boxing process);
back to a value type is known as unboxing. In unboxing process, boxed value type is unboxed
from the heap and assigned to a value type which is being allocated on the stack.
int stackVar = 12;
object boxedVar = stackVar;
int unBoxed = (int)boxedVar;
Conditional Statements:
C# supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
C# has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is True
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
If syntax:
if (condition)
{
// block of code to be executed if the condition is True
}
If –else syntax
if (condition)
{
// block of code to be executed if the condition is True
}
else
{
// block of code to be executed if the condition is False
}
Short if syntax
variable = (condition) ? expressionTrue : expressionFalse;
switch syntax:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
Loop statements:
While loop:
The while loop loops through a block of code as long as a specified condition is True:
while (condition)
{
// code block to be executed
}
Do-while loop:
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
do
{
// code block to be executed
}
while (condition);
For loop:
When you know exactly how many times you want to loop through a block of code, use the for
loop instead of a while loop:
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
For loop can be in the following forms
For Loop without Update
for (statement 1; statement 2; )
{
// code block to be executed
statement 3
}
For Loop without Intialization
statement 1
for (; statement 2; statement 3)
{
// code block to be executed
}
For Loop without Boolean Expression or Condition
for (statement 1;; statement 3)
{
statement 2
// code block to be executed
}
Foreach loop:
There is also a foreach loop, which is used exclusively to loop through elements in an array:
foreach (type variableName in arrayName)
{
// code block to be executed
}
Eg:
using System;
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
Output
1
2
3
4
5
Methods:
A method is a group of statements that together perform a task. Every C# program has at
least one class with a method named Main.
To use a method, you need to:
Define the method
Call the method
Defining Methods in C#
When you define a method, you basically declare the elements of its structure. The syntax for
defining a method in C# is as follows:
<Access Specifier> <Return Type> <Method Nam e>(Param eter List)
{
Method Body
}
Following are the various elements of a method:
Access Specifier: This determines the visibility of a variable or a method from another
class.
In C#, an access specifier is used to control the accessibility of a method. Access specifiers
determine which parts of the code have access to the method. There are several access specifiers
in C#, including:
public: A method declared with the public access specifier is accessible from any part of the
code.
private: A method declared with the private access specifier is only accessible within the same
class.
internal: A method declared with the internal access specifier is accessible within the same
assembly.
protected: A method declared with the protected access specifier is accessible within the same
class and any derived classes.
Here's an example of a method declaration in C# with a private access specifier:
using System;
class Program
{
static void Main(string[] args)
{
// Call the DoSomething method
Program program = new Program();
program.DoSomething();
}
private void DoSomething()
{
Console.WriteLine("Doing something...");
}
}
In this example, the DoSomething method is declared with a private access specifier,
which means it can only be accessed within the Program class. If you tried to call the
DoSomething method from outside the Program class, you would get a compile-time error.
Return type: A method may return a value. The return type is the data type of the value the
method returns. If the method is not returning any values, then the return type is void.
Method name: Method name is a unique identifier and it is case sensitive. It cannot be same
as any other identifier declared in the class.
Parameter list: Enclosed between parentheses, the parameters are used to pass and receive data
from a method. The parameter list refers to the type, order, and number of the parameters of a
method. Parameters are optional; that is, a method may contain no parameters.
Method body: This contains the set of instructions needed to complete the required activity.
Eg:
class NumberManipulator
{
public int FindMax(int num 1, int num 2)
{
int result;
if (num 1 > num 2)
result = num 1;
else
result = num 2;
return result;
}
Calling Methods in C#:
You can call a method using the name of the method. The following example illustrates this:
using System ;
nam espace CalculatorApplication
{
class Num berManipulator
{
public int FindMax(int num 1, int num 2)
{
/* local variable declaration * /
int result;
if (num 1 > num 2)
result = num 1;
else
result = num 2;
return result;
}
static void Main(string[] args)
{
/* local variable definition * /
int a = 100;
int b = 200;
int ret;
Num berManipulator n = new Num berManipulator();
//calling the FindMax m ethod
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}
Recursive Method Call
A method can call itself. This is known as recursion. Following is an example that calculates
factorial for a given number using a recursive function:
using System ;
nam espace CalculatorApplication
{
class Num berManipulator
{
public int factorial(int num )
{
/* local variable declaration * /
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num ;
return result;
}
}
static void Main(string[] args)
{
Num berManipulator n = new Num berManipulator();
//calling the factorial m ethod
Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
}
}
output:
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
Method with no return value:
To
using System;
class Program
{
static void Main(string[] args)
{
PrintMessage();
}
static void PrintMessage()
{
Console.WriteLine("Hello, World!");
}
}
Properties:
Properties are named members of classes, structures, and interfaces. Member variables or
methods in a class or structures are called Fields. Properties are an extension of fields and are
accessed using the same syntax. They use accessors through which the values of the private
fields can be read, written or manipulated. Properties do not name the storage locations. Instead,
they have accessors that read, write, or compute their values.
For example, let us have a class named Student, with private fields for age, name, and code. We
cannot directly access these fields from outside the class scope, but we can have properties for
accessing these private fields.
Accessors
The accessor of a property contains the executable statements that helps in getting
Reading or computing or setting writing the property. The accessor declarations can contain a get
accessor, a set accessor, or both. For example:
// Declare a Code property of type string:
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
// Declare a Name property of type string:
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
// Declare a Age property of type int:
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
Array:
An array stores a fixed-size sequential collection of elements of the same type. An array
is used to store a collection of data, but it is often more useful to think of an array as a collection
of variables of the same type stored at contiguous memory locations. Instead of declaring
individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index. All arrays consist of
contiguous memory locations. The lowest address corresponds to the first element and the
highest address to the last element.
Declaring Arrays
To declare an array in C#, you can use the following syntax:
datatype[] arrayNam e;
where,
datatype is used to specify the type of elements in the array.
[ ] specifies the rank of the array. The rank specifies the size of the array.
arrayName specifies the name of the array.
For example,
double[] balance;
Initializing an Array
Declaring an array does not initialize the array in the memory. When the array variable is
initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array.
For example,
double[] balance = new double[10];
Assigning Values to an Array
You can assign values to individual array elements, by using the index number, like:
double[] balance = new double[10];
balance[0] = 4500.0;
You can assign values to the array at the time of declaration, as shown:
double[] balance = { 2340.0, 4523.69, 3421.0};
When you create an array, C# compiler implicitly initializes each array element to a default value
depending on the array type. For example, for an int array all elements are initialized to 0.
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example,
double salary = balance[9];
The following example, demonstrates the above-mentioned concepts declaration, assignment,
and accessing arrays:
using System ;
nam espace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers * /
int i,j;
/* initialize elem ents of array n * /
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100;
}
/* output each array elem ent's value * /
for (j = 0; j < 10; j++ )
{
Console.WriteLine("Elem ent[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}
}
}
Indexes:
An indexer allows an object to be indexed such as an array. When you define an indexer
for a class, this class behaves similar to a virtual array. You can then access the instance of this
class using the array access operator [].
Syntax
A one dimensional indexer has the following syntax:
elem ent-type this[int index]
{
// The get accessor.
get
{
// return the value specified by index
}
// The set accessor.
set
{
// set the value specified by index
}
}
Use of Indexers
Declaration of behavior of an indexer is to some extent similar to a property. similar to
the properties, you use get and set accessors for defining an indexer. However, properties return
or set a specific data member, whereas indexers returns or sets a particular value from the object
instance. In other words, it breaks the instance data into smaller parts and indexes each part, gets
or sets each part. Defining a property involves providing a property name. Indexers are not
defined with names, but with the this keyword, which refers to the object instance. The following
example demonstrates the concept:
using System ;
nam espace IndexerApplication
{
class IndexedNam es
{
private string[] nam elist = new string[size];
static public int size = 10;
public IndexedNam es()
{
for (int i = 0; i < size; i++)
nam elist[i] = "N. A.";
}
public string this[int index]
{
get
{
string tmp;
if( index >= 0 && index <= size-1 )
{
tmp = namelist[index];
}
else
{
tm p = "";
}
return ( tm p );
}
set
{
if( index >= 0 && index <= size-1 )
{
nam elist[index] = value;
}
}
}
static void Main(string[] args)
{
IndexedNam es nam es = new IndexedNam es();
nam es[0] = "Zara";
nam es[1] = "Riz";
nam es[2] = "Nuha";
nam es[3] = "Asif";
nam es[4] = "Davinder";
nam es[5] = "Sunil";
nam es[6] = "Rubic";
for ( int i = 0; i < IndexedNam es.size; i++ )
{
Console.WriteLine(nam es[i]);
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
Structure:
In C#, a structure is a value type data type. It helps you to make a single variable hold
related data of various data types. The struct keyword is used for creating a structure. Structures
are used to represent a record. Suppose you want to keep track of your books in a library. You
might want to track the following attributes about each book:
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member for your program.
For example, here is the way you can declare the Book structure:
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
}
Features of C# Structures
You have already used a simple structure named Books. Structures in C# are quite
different from that in traditional C or C++.
The C# structures have the following features:
Structures can have methods, fields, indexers, properties, operator methods, and events.
Structures can have defined constructors, but not destructors. However, you cannot define
a default constructor for a structure. The default constructor is automatically defined and
cannot be changed.
Unlike classes, structures cannot inherit other structures or classes.
Structures cannot be used as a base for other structures or classes.
A structure can implement one or more interfaces.
Structure members cannot be specified as abstract, virtual, or protected.
When you create a struct object using the New operator, it gets created and the
appropriate constructor is called. Unlike classes, structs can be instantiated without using
the New operator.
If the New operator is not used, the fields remain unassigned and the object cannot be
used until all the fields are initialized.
Class versus Structure
Classes and Structures have the following basic differences:
classes are reference types and structs are value types
structures do not support inheritance
structures cannot have default constructor
Enumarations:
Enumeration means the action of numbering elements one by one. In C#, enumeration is
done using the keyword enum . C# enum defines a list of elements assigned with an ordered set
of integer values.
C# enum is a value type datatype. It is used to store named integer constants.
The syntax to declare an enum is shown below:
enum EnumName{
CONSTANT_NAME_1,
CONSTANT_NAME_2,
CONSTANT_NAME_N
}
where EnumName is the name given to this enum and with which we can reference.
CONSTANT_NAME_1 , CONSTANT_NAME_2 , . . etc., are the constants inside the enum.
Strings:
In C#, you can use strings as array of characters, However, more common practice is to
use the string keyword to declare a string variable. The string keyword is an alias for the
System.String class.
Creating a String Object
You can create string object using one of the following methods:
By assigning a string literal to a String variable
By using a String class constructor
By using the string concatenation operator +
By retrieving a property or calling a method that returns a string
By calling a formatting method to convert a value or an object to its string representation
Properties of the String Class
The String class has the following two properties:
1.Chars--Gets the Char object at a specified position in the current String object.
2 .Length--Gets the number of characters in the current String object.
Regular Expressions:
A regular expression is a pattern that could be matched against an input text. The .Net
framework provides a regular expression engine that allows such matching. A pattern consists of
one or more character literals, operators, or constructs.
Constructs for Defining Regular Expressions
There are various categories of characters, operators, and constructs that lets you to define
regular expressions. Click the follwoing links to find these constructs.
Character escapes
Character classes
Anchors
Grouping constructs
Quantifiers
Backr eference constructs
Alternation constructs
Substitutions
Miscellaneous constructs
The Regex Class
The Regex class is used for representing a regular expression. It has the following commonly
used
methods:
1 .public bool IsMatchstringinput
2 .public bool IsMatchstringinput, intstartat
3 .public static bool IsMatchstringinput, stringpattern
4 .public MatchCollection Matchesstringinput
5 .public string Replacestringinput, stringreplacement
6 .public string[] Splitstringinput
Collections
Collection classes are specialized classes for data storage and retrieval. These classes
provide support for stacks, queues, lists, and hash tables. Most collection classes implement the
same interfaces. Collection classes serve various purposes, such as allocating memory
dynamically to elements and accessing a list of items on the basis of an index etc. These classes
create collections of objects of the Object class, which is the base class for all data types in C#.
Various Collection Classes and Their Usage
ArrayList : It represents ordered collection of an object that can be indexed individually.It is
basically an alternative to an array. However, unlike array you can add and remove items from a
list at a specified position using an index and the array resizes itself automatically. It also allows
dynamic memory allocation, adding, searching and sorting items in the list.
Hashtable It uses a key to access the elements in the collection. A hash table is used when you
need to access elements by using key, and you can identify a useful key value. Each item in the
hash table has a key/value pair. The key is used to access the items in the collection.
SortedList :It uses a key as well as an index to access the items in a list. A sorted list is a
combination of an array and a hash table. It contains a list of items that can be accessed using a
key or an index. If you access items using an index, it is an ArrayList, and if you access items
using a key , it is a Hashtable. The collection of items is always sorted by the key value.
Stack :It represents a last-in, first out collection of object. It is used when you need a last-in,
first-out access of items. When you add an item in the list, it is called pushing the item and when
you remove it, it is called popping the item.
Queue: It represents a first-in, first out collection of object. It is used when you need a first-in,
first-out access of items. When you add an item in the list, it is called enqueue and when you
remove an item, it is called deque.
BitArray: It represents an array of the binary representation using the values 1 and 0 It is used
when you need to store the bits but do not know the number of bits in advance. You can access
items from the BitArray collection by using an integer index, which starts from zero.