CS2041 UNIT I Question Bank
CS2041 UNIT I Question Bank
Interface
It is users view point. (What
part)
It is used to interact with the
outside world
User is permitted to access the
interfaces only
It
encapsulates the knowledge
about the object.
Implementation
It is suppliers view point.
(How part)
It describes how the delegated
responsibility is carried out.
Functions or methods are
permitted to access the data.
It provides the restriction of
access data by the user.
3
a)Common Language Runtime
o Framework base classes
o User and program Interfaces(ASP.NET and Winforms)
4
Console.WriteLine(Hello, world);
}
}
Compiling and Running the Application
The default file extension for C# programs is .cs, as in hello.cs. Such a program can be
compiled with the command line directive
csc hello.cs
Which produces an executable program named hello.exe. The output of the program is:
Hello, world
12) What are tokens? What are the tokens supported in C# Language?
The smallest, non execuatable ,textual elements in a program are refered to as tokens. The compiler
recognizes them by building up expressions and statements.
In simple sterms,a C# program is a collection of tokens. C# includes the following five types of
tokens :
Keywords
Identifiers
Literals
Operators
Punctuators
Keywords are essential part of language definition. They implement specific features of the
language. They are reserved,and cannot be used as identifiers except when they are prefacedby
the @ character.
Few C# keywords are :
bool
float
namespace
static
byte
For
new
string
char
foreach
private
this
catch
finally
override
throw
5
15) What do you mean by implicit conversion?
It can always be performed without any loss of data. For numeric types, this implies that the destination type
can be fully representing the range of the sources type. For example, a short can be converted implicitly to an
int, because the shott range is a subset of the int range. Therefore, Short b= 75; Int a=b; //implicit conversion.
Are valid statement.
16) What do you mean by explicit conversion?
There are many conversions that cannot be implicitly made between types. If we attempt such conversions, the
complier will give an error message.
17) What are Escape Sequences? Enumerate differenct Esc Sequences.
Escape sequences are special backslash character constants that are used in output methods. For
example '\n' stands for a newline character.There are 3 types of Escape Sequences.They are
(a) Simple
(b) Hexadecimal
(c) Unicode character Escape Sequences
The following tables lists the common Escape Sequences used in C#.
Literal
Meaning
Literal constant Meaning
constant
'\a'
alert
\xhhh
General format of
hexadecimal ES
'\b'
Back space
\uhhhh
General format of
Unicode character
ES
'\f'
Form feed
'\n'
New line
'\r'
Carriage return
'\t'
Horizontal tab
'\v'
Vertical tab
'\''
Single quote
'\'''
Double quote
'\\'
Back slash
'\o'
Null
18) Explain the difference between a Value type and reference type. Illustrate with some
examples
Value types:
* Value types can be created at compile time.
* Stored in stack memory.
* Garbage collector can't access the stack
* value types holds the data directly
* No default values will be stored in value types
* Examples for value types: Predefined datatypes,structures,enums
Reference types:
5
6
* Reference types can be created at run time.
* Stored in heap memory
* Garbage collector can access heap
* Reference types holds the data indiredtly
* Reference types holds default value
* Examples for reference types: Classes,objects,Arrays,Indexers,Interfaces
7
A variable holds a reference to the value, then that type of data types are reference types. These
reference types are stored in heap memory and these types are not fixed in size. They are
maintained in system managed heap but it also uses stack to store reference of the heap. Two
primitive types (string and object) and non-primitive data types (class, interface & delegate) are
examples of reference type.
Ex: class, interface, delegate, string, object and array
20) Define a Class in C#.
A class is a user-defined data type with a template that serves to define it properties. Once a
class type has been defined, we can create variables of that type using declarations wich are
similar to basic type declarations. These variables are known as instances of classes, which are
actual objects.
The syntax for class definition is :
Class className
{
[ variables declaration;]
[ methods declaration;]
}
21) Differntiate Passing by reference and Passing by value.
Passing by Reference vs. Passing by Value
By default, when a value type is passed to a method, a copy is passed instead of the object itself.
Therefore, changes to the argument have no effect on the original copy in the calling method.
You can pass a value-type by reference by using the ref keyword.
When an object of a reference type is passed to a method, a reference to the object is passed. That
is, the method receives not the object itself but an argument that indicates the location of the
object. If you change a member of the object by using this reference, the change is reflected in
the argument in the calling method, even if you pass the object by value.
22) Differentiate value and reference parameters with an example.
Passing Parameters
In C#, arguments can be passed to parameters either by value or by reference. Passing by
reference enables function members, methods, properties, indexers, operators, and constructors
to change the value of the parameters and have that change persist in the calling environment. To
pass a parameter by reference, use the ref or out keyword. For simplicity, only the ref keyword
is used in the examples in this topic.
The following example illustrates the difference between value and reference parameters.
class Program
{
static void Main(string[] args)
{
7
8
int arg;
// Passing by value.
// The value of arg in Main is not changed.
arg = 4;
squareVal(arg);
Console.WriteLine(arg);
// Output: 4
// Passing by reference.
// The value of arg in Main is changed.
arg = 4;
squareRef(ref arg);
Console.WriteLine(arg);
// Output: 16
}
static void squareVal(int valParameter)
{
valParameter *= valParameter;
}
// Passing by reference
static void squareRef(ref int refParameter)
{
refParameter *= refParameter;
}
}
23) What is a signature of a method?
Method Signatures
Methods are declared in a class or struct by specifying the access level such as public or private,
optional modifiers such as abstract or sealed, the return value, the name of the method, and any
method parameters. These parts together are the signature of the method.
24) Explain with examples the purpose of Constructor/Destructor
Constructors are special methods, used when instantiating a class. A constructor can never return
anything, which is why you don't have to define a return type for it. A normal method is defined
like this:
For example, we have a Car class, with a constructor which takes a string as argument. Of
course, a constructor can be overloaded as well, meaning we can have several constructors, with
the same name, but different parameters. Here is an example:
public Car()
{
}
public Car(string color)
{
this.color = color;
8
9
}
If you run this code, you will see that the constructor with no parameters is called first. This can be
used for instantiating various objects for the class in the default constructor, which can be called
from other constructors from the class. If the constructor you wish to call takes parameters, you
can do that as well. Here is a simple example:
public Car(string color) : this()
{
this.color = color;
Console.WriteLine("Constructor with color parameter called!");
}
public Car(string param1, string param2) : this(param1)
{
}
If you call the constructor which takes 2 parameters, the first parameter will be used to
invoke the constructor that takes 1 parameter.
Destructors
Since C# is garbage collected, meaning that the framework will free the objects that you no
longer use, there may be times where you need to do some manual cleanup. A destructor, a
method called once an object is disposed, can be used to cleanup resources used by the
object. Destructors doesn't look very much like other methods in C#. Here is an example of
a destructor for our Car class:
~Car()
{
Console.WriteLine("Out..");
}
Once the object is collected by the garbage collector, this method is called.
25) How will you create objects of a class?
Creating an object is referred to as instantiating an object. Objects in C# are created ujsing the new
operator.
EXAMPLE
Class Rectangle
{
Int length;
Int width;
Public void GetData(int x, int y)
{
Length = x;
Width = y;
}
}
Object creation steps :
(1) Declare class Rectangle as shown above.
(2) Create an object of type Rectangle :
9
10
Rectangle rect1; // declare the variable to hold reference
(3) Rect1 = new Rectangle(); // instantiate ( Assigns the object reference to the variable)
Steps (2) and (3) can be combined into one as shown below :
Rectangle rect1 = new Rectangle();
Action
Statement
Declare
variable
rect1 of
type
Rectangle
Instantiate
Rectangle rect1;
Result
Rect1 is the variable to hold
the object reference
Null
rect1
Rect1 = new
Rectangle( );
Rectangle object
11
Class test
{
Public static void Main()
{
Rectangle rect1 = new Rectangle(15,10); // calling constructor
.
}
28) Explain the usage of this reference.
this
The this keyword refers to the current instance of the class. Static member functions do not have
a this pointer. The this keyword can be used to access members from within constructors,
instance methods, and instance accessors.
The following are common uses of this:
To qualify members hidden by similar names:
example:
public Employee(string name, string alias)
{
this.name = name;
this.alias = alias;
}
29) What are access modifiers? Explain their purpose.
Access Modifiers
Access modifiers are keywords used to specify the declared accessibility of a member or a type.
public
protected
internal
private
public
The public keyword is an access modifier for types and type members. Public access is the most
permissive access level. There are no restrictions on accessing public members.
11
12
private
The private keyword is a member access modifier. Private access is the least permissive access
level. Private members are accessible only within the body of the class or the struct in which they
are declared.
protected
The protected keyword is a member access modifier. A protected member is accessible from
within the class in which it is declared, and from within any class derived from the class that
declared this member.
A protected member of a base class is accessible in a derived class only if the access takes place
through the derived class type. For example, consider the following code segment:
internal
The internal keyword is an access modifier for types and type members. Internal members are
accessible only within files in the same assembly.
A common use of internal access is in component-based development because it enables a group
of components to cooperate in a private manner without being exposed to the rest of the
application code. For example, a framework for building graphical user interfaces could provide
Control and Form classes that cooperate using members with internal access. Since these
members are internal, they are not exposed to code that is using the framework.
30) Differentiate static and non-static members of a class.
C# Static Method
Static methods have no instances. They are called with the type name, not an instance identifier.
They are slightly faster than instance methods because of this. Static methods can be public or
private. They cannot use the this instance expression.
Static Modifier
Key point:Static methods are called without an instance reference.
Example
This program defines both static methods and regular instance methods and calls them both. The
static methods use the static keyword somewhere in the method declaration signature, usually as
the first keyword or the second keyword after public.
12
13
Static methods cannot access non-static class level members and do not have a 'this' pointer.
Instance methods can access those members, but must be called through an object instantiation,
which causes another step and level of indirection.
31) What is enumeration?
Enumeration is a user-defined integer type which provide a way for attaching names to numbers.
32) Explain the syntax for declaring data type enumeration and give examples.
An enumeration (enum) is a value data type. It is a special integer data type. The declaration of this
data type defines a type name for a related group of symbolic constants. The associating integral data
type is known as underlying data type.
The syntax for defining enum is
Enum enumBase[:dataType]
{
Enumerator1,
Enumerator2,
.
enumeratorN
}
Where
Enum is a keyword indicating enumerator data type.
Enum Base is the name used to identify the specific enumeration.
Data type is one of the types from byte,sbyte,short,ushort,int,uint,long, or ulong.
Enumerator1,enumerator2,enumeratorN are list of identifiers representing enum members.
EXAMPLE
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
// Inside some method
Days day1, day2;
int day3;
day1 = Days.Sat;
day2 = Days.Tue;
day3 = (int) Days.Fri;
Console.WriteLine(day1);
Console.WriteLine(day2);
Console.WriteLine(day3);
Output : Sat
Tue
6
13
14
class
Data Type
Value type
Reference type
Storage type
Stack
Heap
Inheritance
Not supported
Supported
Default values
zero
Null
Field
Not permitted
permitted
initialization
Construcor
Not allowed
Allowed
Destructors
Not supported
Supported
Assignment
Copies the values
Copies the reference
operation
34) What is type conversion? Explain with examples.
A data type can be explicitly converted into a desired data type. This feature is known
as casting. It is accomplished by using the cast operator.
The general format for type conversion :
(data type) expression
Example
(long) (10+25) converts the integer constant 35 to long.
(float) 1 converts the integer constant 1 to the float value 1.0
35) Explain boxing and unboxing.
Boxing
Conversion of value type to an object type is known as boxing. Boxing permits an implicit conversion of
value type to an object type. Boxing a value means allocating an object instance , and the value of the
value type is copied into that object instance.
Example
The following is the value type declaration :
Int x = 256;
The following statement implicitly applies the boxing operation on the variable x :
Object obj = x;
The value of variable x is stored on stack and it can be directly accessed. The boxing of x results in
allocating memory on stack for obj reference and memory for data on heap.
Unboxing
Unboxing performs the opposite operationnof boxing. Conversion of object type to value type is known
as Unboxing.
Example
Object obj = 256;
Int x = (int)obj; // unboxing
36) Explain checked and unchecked operators.
14
15
Overflow checking for arithmetic operations and conversion of integer types are
controlled by checked and unchecked operators.
If an operation is checked, an overflow error will be thrown when an overflow occurs.
If it is not checked , the error is not reported and the overflowing bits are discarded.
Example
Int p = checked ( x * y ); // will check for the overflow if any, and an error is
reported(or an exception is thrown).
The code
Int p = unchecked ( x * y) ; // will result in loss of bits when an overflow occurs.
37) Explain with syntax and flowchart a) While loop construct b) Do while loop construct
c)for loop construct
While loop construct Do While loop construct for loop construct
While (boolExpr)
Do
for (Expr_1; boolExpr; expr_2)
{
[
{
embedStmt;
embedStmt;
embedStmt;
}
}
}
While (boolExpr);
38) What are exceptions and How exceptions are handled in C# programs?
During execution of a program, an unexpected situation or errors may occur and
they are called exceptions. When an exception occurs , the linear flow of control through the
program is altered. When an exception is thrown, the CLR searches for a method that
can handle the exception. An exception handler is used to catch the exception that is thrown.
Exception handling is an in built mechanism in .NET framework to detect and handle run time
errors. Exceptions are defined as anomalies that occur during the execution of a program. The
.NET framework provides a rich set of standard exceptions that are used during exceptions
handling.
39) Give examples of predefined Exception classes in C#.
Sno
Exception Type
remarks
1
ArgumentException
Invalid argument
2
ArithmeticException
Arithmetic Overflow or Underflow
3
IndexOutOfRangeException An array index is out of range
4
StackOverflowException
Stack overflow error
5
DivideByZeroException
Error by dividing a value by zero
6
ArgumentNullException
A null argument is passed to a method
resulting in an error
40) Explain briefly the exception handling mechanism in C#.
Exception handling is an in built mechanism in .NET framework to detect and handle run time
errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that
occur during the execution of a program. They can be because of user, logic or system errors.
C# provides three keywords try, catch and finally to do exception handling. The try encloses the
statements that might throw an exception whereas catch handles an exception if one exists. The finally
can be used for doing any clean up process.
15
16
The general form try-catch-finally in C# is shown below
try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}
If any exception occurs inside the try block, the control transfers to the appropriate catch block and
later to the finally block.
41) Explain the syntax of a) the throw statement b) the try statement c) user defined exceptions
// try_catch_example.cs
using System;
class MainClass
{
static void ProcessString(string s)
{
if (s == null)
{
throw new ArgumentNullException();
}
}
static void Main()
{
try
{
string s = null;
ProcessString(s);
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
---------------------------------------------------------// try_catch_finally.cs
using System;
public class EHClass
{
16
17
static void Main()
{
try
{
Console.WriteLine("Executing the try statement.");
throw new NullReferenceException();
}
catch (NullReferenceException e)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
catch
{
Console.WriteLine("Caught exception #2.");
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
Sample Output
Executing the try statement.
System.NullReferenceException: Object reference not set to an instance of an object.
at EHClass.Main() Caught exception #1.
Executing finally block.
42) Write C# program to illustrate exception handling a) for stack over flow b) divide by zero
exception
Example-2
using System;
class Program
{
static void Main()
{
try
{
int value = 1 / int.Parse("0");
Console.WriteLine(value);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
17
18
}
The Program output
Attempt to divide by zero
43) Explain with an example how DivideByZero exception is handled in C#.
class ExceptionTest
{
static double SafeDivision(double x, double y)
{
if (y == 0)
throw new System.DivideByZeroException();
return x / y;
}
static void Main()
{
double a = 98, b = 0;
double result = 0;
try
{
result = SafeDivision(a, b);
Console.WriteLine("{0} divided by {1} = {2}", a, b, result);
}
catch (DivideByZeroException e)
{
Console.WriteLine("Attempted divide by zero.");
}
}
}
44) Define an array.
An array is a data structure that contains a number of subscripted variables. Each subscripted variable is
Known as an element of the array. All the elements are of the same data type.
An array is a reference data type in C#.
45) Explain array declaration and instantiation in C# with an example.
Syntax for array declaration
dataType[ ] arrayName; //declares a reference to an array
arrayName = new dataType[size]; // allocates memory
Example-1
Float[ ] x; // declaration of an array
X = new float[5]; // array has 5 elements
The first statement creates an one-dimensional array x. In the second statement , memory allocated
Using the new operator.
18
19
Example-2
Char[ ] str;
Str = new char[20];
Example-3
Int k = 25;
Float[] f;
F = new float[k];
46) Explain declaration and instantiation of a two dimensional array in C#.
Syntax for 2D array declaration ;
dataType [ , ] arrayName; // declaration of a 2D array
arrayName = new dataType[size1,size2]; // size1, and size2 are the no of rows
and no of columns resp.
Example-1
Int[ , ] s = new int[3,2]; // Defines a two-dimensional integer array a.
Example-2
Char[ , ] s = new char[10,20]; // 2D array to hold 200 elements
47) Write short notes on a) creation of three dimensional arrays b)creation of jagged arrays
The syntax for creating Three-dimensional array
dataType[ , , ] arrayName;
arrayName = new dataType[size1,size2,size3];
Example
Char[ , , ] book; // Declares a 3-dimensional array book
Book = new char[20, 40, 80]; // creates 3D array book
48) Tabulate the difference between regular and jagged arrays.
S. No
1
2
3
4
Regular array
Array of elements of non-array type
Multi dimensional array subscripts are
separated by comma within an open
and closing square brackets
Shapes are regular
Declaration contains only one pair of
square brackets
Jagged array
Array of elements of array type
Each array subscripts is enclosed
within separate square brackets
Shapes are irregular
Declaration contains two or more
pairs of square brackets
19
20
21
// Create an ArrayList and add three elements.
//
ArrayList list = new ArrayList();
list.Add("One");
list.Add("Two");
list.Add("Three");
}
}
21
22
22
23
Managed Code
The second level of compilation happens just before the application is executed. At this point, the IL code is
compiled into low-level native machine code. This stage is known-as Just-In-Time (JIT) Compilation.
Finally .NET CLR produces the executable or library files and executes the code.
Managed Code
Code developed and running under the control of the CLR is often termed managed code
Microsoft shared the idea of IL code from Java byte code in which IL code can be quickly translated into native
machine code. In other words, by compiling to IL code, you obtain platform independence for .NET in much
same way as compiling java code.
23
24
IL code is compiled (JIT compilation), whereas java byte code was interpreted. One of the advantages of java
was that, on execution, the process of translating from java byte code to native executable resulted in loss of
performance. Instead of compiling the entire applications in one go; the JIT compiler simply compiles each
portion of code. This is why we can expect that execution of managed IL code will be as fast as executing native
code.
IL is the backbone for every managed application. In a sense, the language is only recognized by .NET
framework is IL.
access to data;
All classes implemented in the .NET class library are organized into namespaces. Each namespace contains
classes and other types that are related to the specific task or set of tasks input/output operations, web
applications creation, working with data and XML, and so on. Table 3.1 shows the most important namespaces
in the .NET class library.
Table 3.1. The main namespaces in the .NET class library
Namespace
System
Description
Contains fundamental classes and base classes that define common value and
reference data types, events and event handlers, interfaces, processing exceptions,
data conversion, mathematics, as well as garbage collection and application
environment management. Some of the classes defined in the namespace are
covered in this chapter and also in Chapters 4 and 5.
24
25
Namespace
Description
System.IO
Provides classes that support asynchronous and synchronous reading from and
writing to data streams and files. Contains classes like FileStream,
MemoryStream, Path, and Directory. We will learn about this namespace and its
classes in the next chapter.
System.Collections
Contains interfaces and classes that define various collections of objects, such as
lists, arrays, hash tables, stacks, queues, and dictionaries. The classes defined in
this namespace are covered in this chapter.
System.Threading
System.Reflection
Contains classes that provide dynamic binding and a managed view of loaded
types, methods, and fields. Contains classes such as Assembly, Module, and
MethodInfo.
System.Security
System.Net
Provides support for network programming. Includes, for example, the classes
HttpWebRequest, IPAddress, Dns, and Connection. We will learn about this
namespace and its classes in the next chapter.
System.Data
System.XML
System.Web
25
26
Namespace
Description
System.Web.Services
System.Windows.Forms
System.Drawing
System.Globalization
System.Resources
After this brief overview of most of the chapters in the book, we are ready to start our journey through the .NET
Framework class library. Main namespaces are shown in Figure 3.1. Our first stop is a little bit unusual
instead of covering the Object class that is, the ultimate ancestor for all of the classes in the .NET Framework
class library we will discuss the Console class. The following section will explain why we do this.
Figure 3.1. Main namespaces in the .NET framework class library
26
27
In Visual Basic.NET, we create a console application by creating a new module that contains one subroutine
called Main this is the entry point into our console application (see Figure 3.2):
Figure 3.2. Console application in action
28
if (i > 0)
Console.WriteLine("The number {0} is positive", i);
else
Console.WriteLine("The number {0} is not positive", i);
//multicase selection
if (i == 0)
Console.WriteLine("The number is zero");
else if (i > 0)
Console.WriteLine("The number {0} is positive", i);
else
Console.WriteLine("The number {0} is negative", i);
The variable i is the object of evaluation here. The expression in an if statement must resolve to a boolean
value type.
// Compiler Error
if (1)
Console.WriteLine("The if statement executed");
Console.ReadLine();
When the C# compiler compiles the preceding code, it generates the error "Constant value 1 cannot be
converted to bool."
Listing 5.24 shows how conditional or (||) and conditional and (&&) operators are used in the same manner.
Listing 5.24: If-Then-Else Example 2
//Leap year
int year = 1974;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
Console.WriteLine("The year {0} is leap year ", year);
else
Console.WriteLine("The year {0} is not leap year ", year);
Switch
From the example in Listing 5.25, you can see that the switch statement is similar to an if-else ifelse if-else
form of an if statement.
Listing 5.25: Switch Example 1
string day = "Monday";
Console.WriteLine("enter the day :");
day = Console.ReadLine();
switch (day)
{
28
29
case "Mon":
break;
case "Monday":
Console.WriteLine("day is Monday: go to work");
break;
default:
Console.WriteLine("default");
break;
}
switch (strVal1)
{
case "reason1":
goto case "reason2"; // this is a jump to mimic fall-through
case "reason2":
intOption = 2;
break;
case "reason 3":
intOption = 3;
break;
case "reason 4":
intOption = 4;
break;
case "reason 5":
intOption = 5;
break;
default:
intOption = 9;
break;
}
Do-While
The while loop allows the user to repeat a section of code until a guard condition is met. Listing 5.27 presents a
simple while loop designed to find out the number of digits in a given value.
Listing 5.27: While Example
//find out the number of digits in a given number
int i = 123;
int count = 0;
int n = i;
//while loop may execute zero times
while (i > 0)
{
++count;
i = i / 10;
}
29
30
Console.WriteLine("Number {0} contains {1} digits.", n, count);
For a given number i = 123, the loop will execute three times. Hence the value of the count is three at the end
of the while loop.
This example has one logical flaw. If the value of i is 0, the output of the code will be "Number 0 contains 0
digits." Actually, the number 0 contains one digit. Because the condition of the while loop i > 0 is false from
the beginning for the value i = 0, the while loop does not even execute one time and the count will be zero.
Listing 5.28 presents a solution.
Listing 5.28: Do Example
//find out the number of digits in a given number
int i = 0;
int count = 0;
int n = i;
do
{
++count;
i = i / 10;
} while (i > 0);
Console.WriteLine("Number {0} contains {1} digits.", n, count);
The do-while construct checks the condition at the end of the loop. Therefore, the do-while loop executes at
least once even though the condition to be checked is false from the beginning.
For
The for loop is useful when you know how many times the loop needs to execute. An example of a for
statement is presented in Listing 5.29.
Listing 5.29: For Example 1
for (int i = 0; i < 3; i++)
a(i) = "test"
for (string strServer = Console.ReadLine();
strServer != "q" && strServer != "quit";
strServer = Console.ReadLine())
{
Console.WriteLine(strServer);
}
Listing 5.30 shows the use of a for loop with the added functionality of break and continue statements.
//For loop with break and continue statements
for (int i = 0; i < 20; ++i)
{
if (i == 10)
30
31
break;
if (i == 5)
continue;
Console.WriteLine(i);
}
The output of the code in the listing is as follows:
0
1
2
3
4
6
7
8
9
When i become 5, the loop skips over the remaining statements in the loop and goes back to the post loop
action. Thus, 5 is omitted from the output. When i become 10, the program will break out of the loop.
ForEach
The foreach statement allows the iteration of processing over the elements in arrays and collections. Listing
5.31 contains a simple example.
Listing 5.31: ForEach Example 1
//foreach loop
string[] a = { "Chirag", "Bhargav", "Tejas" };
foreach (string b in a)
Console.WriteLine(b);
Within the foreach loop parentheses, the expression consists of two parts separated by the keyword in. To the
right of in is the collection, and to the left is the variable with the type identifier matching whatever type the
collection returns.
Listing 5.32 presents a slightly more complex version of the foreach loop.
Listing 5.32: ForEach Example 2
Int16[] intNumbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (Int16 i in intNumbers)
{
System.Console.WriteLine(i);
}
Each iteration queries the collection for a new value for i. As long as the collection intNumbers returns a value,
the value is put into the variable i and the loop will continue. When the collection is fully traversed, the loop
31
32
will terminate.
GoTo
You can use the goto statement to jump to a specific segment of code, as shown in Listing 5.33. You can also
use goto for jumping to switch cases and default labels inside switch blocks. You should avoid the overuse of
goto because code becomes difficult to read and maintain if you have many goto jumps within your code.
Listing 5.33: GoTo Example
label1:
;
//...
if (x == 0)
goto label1;
//...
Break
The break statement, used within for, while, and do-while blocks, causes processing to exit the innermost loop
immediately. When a break statement is used, the code jumps to the next line following the loop block, as
you'll see in Listing 5.34.
Listing 5.34: Break Example
while (true)
{
//...
if (x == 0)
break;
//...
}
Console.WriteLine("break");
Continue
The continue statement (shown in Listing 5.35) is used to jump to the end of the loop immediately and process
the next iteration of the loop.
Listing 5.35: Continue Example
int x = 0;
while (true)
{
//...
if (x == 0)
{
x = 5;
continue;
32
33
}
//...
if (x == 5)
Console.WriteLine("continue");
//...
}
Return
The return statement is used to prematurely return from a method. The return statement can return empty or
with a value on the stack, depending upon the return value definition in the method (Listing 5.36 shows both).
Void methods do not require a return value. For other functions, you need to return an appropriate value of the
type you declared in the method signature.
Listing 5.36: Return Example
void MyFunc1()
{
// ...
if(x == 1)
return;
// ...
}
int MyFunc2()
{
// ...
if(x == 2)
return 1919;
// ...
}
4. Explain in detail about various operators available in C#.
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C# has rich
set of built-in operators and provides the following type of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
33
34
Misc Operators
This tutorial explains the arithmetic, relational, logical, bitwise, assignment, and other operators one by one.
Arithmetic Operators
Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10 and variable B holds
20 then:
Show Examples
Operator Description
Example
A + B = 30
A - B = -10
A * B = 200
B / A= 2
++
A++ = 11
--
A-- = 9
Relational Operators
Following table shows all the relational operators supported by C#. Assume variable A holds 10 and variable B holds
20, then:
Show Examples
Operator Description
Example
==
!=
(A != B) is true.
34
35
>
<
(A < B) is true.
>=
<=
Logical Operators
Following table shows all the logical operators supported by C#. Assume variable A holds Boolean value true and
variable B holds Boolean value false, then:
Show Examples
Operator Description
Example
&&
(A && B) is false.
||
(A || B) is true.
Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows:
p
p&q
p|q
p^q
1
35
36
1
Assume if A = 60; and B = 13; then in the binary format they are as follows:
A = 0011 1100
B = 0000 1101
----------------A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C# are listed in the following table. Assume variable A holds 60 and variable B
holds 13, then:
Show Examples
Operator Description
Example
&
Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, which is 0011 1101
<<
36
37
>>
Assignment Operators
There are following assignment operators supported by C#:
Show Examples
Operator Description
Example
+=
C += A is equivalent to C = C + A
-=
*=
C *= A is equivalent to C = C * A
/=
C /= A is equivalent to C = C / A
%=
C %= A is equivalent to C = C % A
<<=
>>=
&=
^=
C ^= 2 is same as C = C ^ 2
|=
C |= 2 is same as C = C | 2
37
38
Miscillaneous Operators
There are few other important operators including sizeof, typeof and ? : supported by C#.
Show Examples
Operator Description
Example
sizeof()
sizeof(int), returns 4.
typeof()
typeof(StreamReader);
&
Pointer to a variable.
?:
Conditional Expression
is
as
Operator Precedence in C#
Operator precedence determines the grouping of terms in an expression. This affects evaluation of an expression.
Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence
than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so the first
evaluation takes place for 3*2 and then 7 is added into it.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.
Within an expression, higher precedence operators are evaluated first.
Show Examples
38
39
Category
Operator
Associativity
Postfix
() [] -> . ++ - -
Left to right
Unary
Right to left
Multiplicative
*/%
Left to right
Additive
+-
Left to right
Shift
<< >>
Left to right
Relational
Left to right
Equality
== !=
Left to right
Bitwise AND
&
Left to right
Bitwise XOR
Left to right
Bitwise OR
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
Right to left
Comma
Left to right
In C# programming, string is another kind of data type that represents Unicode Characters. It is
the alias of System.String however, you can also write System.String instead of string. It is the
sequence of character in which each character is a Unicode character.
39
40
There is no difference between string and String because string is the alias of System.String.
Most of the developers get confused what to use between sting and String. Technically there is
no difference between them and they can use any of them. However, you will have to use using
System to use the String in C#. Another difference is String is a class name whereas string is a
reserved keyword. You should always use string instead of String.
String Functions
Definitions
Clone()
CompareTo()
Contains()
EndsWith()
Equals()
GetHashCode()
GetType()
GetTypeCode()
IndexOf()
ToLower()
ToUpper()
Insert()
IsNormalized()
LastIndexOf()
Length
Remove()
Replace()
41
Split()
StartsWith()
Substring()
ToCharArray()
Trim()
42
Console.WriteLine(firstname.ToLower());
//Covert string into lower case
Console.WriteLine(firstname.ToUpper());
//Convert string into Upper case
Console.WriteLine(firstname.Insert(0, "Hello")); //Insert substring into string
Console.WriteLine(firstname.IsNormalized());
//Check Whether string is in Unicode normalization
from C
Console.WriteLine(firstname.LastIndexOf( "e")); //Returns the last index position of specified
value
Console.WriteLine(firstname.Length);
//Returns the Length of String
Console.WriteLine(firstname.Remove(5));
//Deletes all the characters from begining to specified index.
Console.WriteLine(firstname.Replace( 'e','i')); // Replace the character
string[] split = firstname.Split( new char[] { 'e' }); //Split the string based on specified value
Console.WriteLine(split[0]);
Console.WriteLine(split[1]);
Console.WriteLine(split[2]);
Console.WriteLine(firstname.StartsWith( "S")); //Check wheter first character of string is same
as specified value
Console.WriteLine(firstname.Substring(2,5));
//Returns substring
Console.WriteLine(firstname.ToCharArray());
//Converts an string into char array.
Console.WriteLine(firstname.Trim());
//It removes starting and ending white spaces from
string.
}
}
}
Output
Steven Clark
1
True
False
False
42
43
1470518261
System.String
String
2
steven clark
STEVEN CLARK
HelloSteven Clark
True
4
12
Steve
Stivin Clark
St
v
n Clark
True
even
Steven Clark
Steven Clark
44
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday
}
class Program
{
static void Main(string[] args)
{
attandance present = attandance.Monday;//Valid
Console.WriteLine(present);
//attandance absent = attandance.Sunday;//Invalid
Console.ReadLine();
}
}
}
Output
Monday
In the preceding example, we create attendance enumeration in which 5 values are assigned as
Monday, Tuesday, Wednesday, Thursday and Friday. Only these 5 values are valid entry for
attendance enumeration variable. If you assign other entry as Sunday or Saturday, it will be
invalid and you will get compile time error in C# programming.
Structures
44
45
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;
};
The following program shows the use of the structure:
using System;
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
45
46
47
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
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.
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.
47
48
Class versus Structure
Classes and Structures have the following basic differences:
In the light of the above discussions, let us rewrite the previous example:
using System;
struct Books
{
private string title;
private string author;
private string subject;
private int book_id;
public void getValues(string t, string a, string s, int id)
{
title = t;
author = a;
subject = s;
book_id = id;
}
public void display()
{
Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}", book_id);
}
};
48
49
50
Book_id : 6495407
Title : Telecom Billing
Author : Zara Ali
Subject : Telecom Billing Tutorial
Book_id : 6495700
When you define a class, you define a blueprint for a data type. This does not actually define any data, but it
does define what the class name means. That is, what an object of the class consists of and what operations can be
performed on that object. Objects are instances of a class. The methods and variables that constitute a class are called
members of the class.
Defining a Class
A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of
curly braces. Following is the general form of a class definition:
<access specifier> class class_name
{
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list)
{
// method body
}
<access specifier> <return type> method2(parameter_list)
50
51
{
// method body
}
...
<access specifier> <return type> methodN(parameter_list)
{
// method body
}
}
Note:
Access specifiers specify the access rules for the members as well as the class itself. If not mentioned, then
the default access specifier for a class type is internal. Default access for the members is private.
Data type specifies the type of variable, and return type specifies the data type of the data the method
returns, if any.
To access the class members, you use the dot (.) operator.
The dot operator links the name of an object with the name of a member.
52
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
double volume = 0.0;
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
52
53
Member Functions and Encapsulation
A member function of a class is a function that has its definition or its prototype within the class definition similar to any
other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class
for that object.
Member variables are the attributes of an object (from design perspective) and they are kept private to implement
encapsulation. These variables can only be accessed using the public member functions.
Let us put above concepts to set and get the value of different class members in a class:
using System;
namespace BoxApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public void setLength( double len )
{
length = len;
}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
public double getVolume()
{
53
54
return length * breadth * height;
}
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box();
double volume;
// Declare Box2 of type Box
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}" ,volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
54
55
}
}
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
C# Constructors
A class constructor is a special member function of a class that is executed whenever we create new objects of that
class.
A constructor has exactly the same name as that of class and it does not have any return type. Following example
explains the concept of constructor:
using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line()
{
Console.WriteLine("Object is being created");
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
55
56
}
static void Main(string[] args)
{
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
A default constructor does not have any parameter but if you need, a constructor can have parameters. Such
constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the
time of its creation as shown in the following example:
using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line(double len) //Parameterized constructor
{
Console.WriteLine("Object is being created, length = {0}", len);
length = len;
}
56
57
57
58
Destructor can be very useful for releasing memory resources before exiting the program. Destructors cannot be
inherited or overloaded.
Following example explains the concept of destructor:
using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line() // constructor
{
Console.WriteLine("Object is being created");
}
~Line() //destructor
{
Console.WriteLine("Object is being deleted");
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line();
58
59
60
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.WriteLine("Variable num for s1: {0}", s1.getNum());
Console.WriteLine("Variable num for s2: {0}", s2.getNum());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Variable num for s1: 6
Variable num for s2: 6
You can also declare a member function as static. Such functions can access only static variables. The static functions
exist even before the object is created. The following example demonstrates the use of static functions:
using System;
namespace StaticVarApplication
{
60
61
class StaticVar
{
public static int num;
public void count()
{
num++;
}
public static int getNum()
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s = new StaticVar();
s.count();
s.count();
s.count();
Console.WriteLine("Variable num: {0}", StaticVar.getNum());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Variable num: 3
61