Professional Documents
Culture Documents
for
C# Programming
COURSE CODE:
COURSE: BCA
SEMESTER: V
YEAR: 2015-16
Table of Content
SN
CONTENTS
PAGE NO
Course Outline
Study Notes
Assigment-1
Assigment-2
1. Course Code:
2. Course Title: C# Programming
3. Course Overview:
C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and
approved by European Computer Manufacturers Association (ECMA) and International Standards
Organization (ISO). C# was developed by Anders Hejlsberg and his team during the development
of .Net Framework.
C# is designed for Common Language Infrastructure (CLI), which consists of the executable code
and runtime environment that allows use of various high-level languages on different computer
platforms and architectures. The Integrated Development Environment (IDE) available for C#
provides immediate error correction, strong typing, refactoring and reformatting. Students shall
be exposed to such tools for the development of code.
The course will address the basics of the programming language, the need for its study, the
features of the language and subsequently developing program code. The following questions
will be answered during the course:
a) Why do we need to study C#?
b) How C# is different from other programming languages?
c) How it implements object oriented concepts of programming?
d) What are the basic building blocks of C#?
e) How to develop and execute programs in C# using control statements and loops?
f) How namespaces are developed and used in C#?
g) What are delegates and events in c#?
h) How to use LINQ in C#?
This course will equip the students with an understanding of the fundamental principles of the
language. The students are expected to review the course readings and the indicated portion
of the prescribed text for class discussions prior to attending each session.
4. Course objective :
The objective of the course is to introduce object oriented programming using C#, the
student will be able to use C# for implementing OOP concepts.
5. Learning Outcome:
After undergoing this course, the student will be able to:
CO1: Understand the basics of C#, its data types, variables, operators, namespaces,
control statements and looping.
CO2: Understand Methods and Arrays in C#.
CO3: Classes and objects in C# and understand the concept constructors, Properties
and Indexers.
CO4: Inheritance and Static and Dynamic Polymorphism.
CO5: Interfaces in a C# program
CO6: Delegates, Events and LINQ .
CO7: Implement exception handling in C#.
Contents/Concepts
Module I:Introduction to C#
Features of C#
Dot Net Framework
Compilation and execution of C#
program
Keywords in C#
Namespaces Declaration
Value type and reference type
Type conversion
Variable Declaration and Initialization,
4
Var Variable
Operators in C#
Control Statements
looping
Module II: Methods and Arrays
Defining and Calling Methods
Method Parameters
Declaration and Initialization of Arrays and
applications
Multidimensional Array and Jagged Array
String, String Methods and foreach loop
Module III: Classes and Objects
OOP Concepts
Defining Class and Member access
Modifiers
Constructors and Destructors
Constant members
this keyword
Properties and Auto Implemented properties
Object initializer and Collection Initializer
Partial methods and Partial Classes
Indexers
Module IV: Inheritance and Polymorphism
Module V: Interfaces
Defining and extending Interfaces
Interface and Inheritance
Explicit Interface
Module VI: Delegates and Events
Delegates, Delegate Methods and Multicast
Delegates
Events
LINQ
7. Session Plan:
Module I: Introduction to C#
Session
Topics
Learning
Resources
Pg.4
features of C#
1
Dot Net Framework
Pg.13
Hand out
2
Compilation and
execution of C#
program
Namespaces
Declaration
Pg.20
Keywords in C#
Hand out
Hand out
Pg.40
Learning
Outcomes
To know the Dot
Net framework
and able to list out
the features of the
language.LO1
Be able to
understand how
the compilation
and execution is
done and
namespaces and
keywords in C#.
LO1
Understand and
execute first C#
program and
understand the
value and
reference
type.LO1
Type conversion
boxing and unboxing
Var Variable
Pg.65
To understand
type
conversionand var
variable. LO1
Operators in C#
Pg.55
Understand
Pg.80
Operators in C#
statements.
LO1
Pg.125
Method parameters
7
8
Pg.129
To understand
how to define and
call methods.
LO2
Understand the
method
parameters.LO2
Understand arrays
in c#.LO2
Declaration and
Initialization of Arrays
Pg.143
Pg.150
Applications and
Multidimensional
arrays
To understand
multidimensional
arrays. LO2
10
Jagged arrays
Pg.152
11
foreach loop
Pg.113
12
Pg.168
Understand
jagged arrays.
LO2
Understand
foreach loop.LO2
Understand
Strings and string
methods. LO2
15
16
Member access
modifiers
Programs using
member access
Hand out
Pg.212
Pg.216
Pg.216
To understand the
OOP concepts. LO3
Understand how to
define classes in C#.
LO3
Understand the
access modifiers in
C#. LO3
Understand the
programs using
modifiers
17
Default constructor
Parameterized
constructor
Pg.219
Overloaded
Constructor
Pg.221
19
Static Constructor
Copy Constructor
Pg. 223
20
Destructors
Pg.224
21
Constant Members
Pg.227
22
this keyword
Pg.225
23
Properties
Pg.228
24
Auto Implemented
Properties
Hand out
25
Hand out
26
Hand out
27
Hand out
18
28
Pg. 230
member access
modifiers .LO3
Know default
constructor
Parameterized
constructor. LO3
How overloading of
constructor is done
in C#. LO3
Understand the Static
and copy
Constructor. LO3
Understand the
concept of
Destructors.LO3
Understand the
constant
members.LO3
understand this
keyword LO3
understand the
concept of Properties
LO3
Understand Auto
Implemented
Properties. LO3
Understand Object
and collection
initializer.LO3
Understand Partial
methods and partial
classes.LO3
Can implement
Partial Methods and
Partial classes.LO3
Understand and
implement
Indexers.LO3
29
Introduction to
Inheritance and its
types
Pg.244
30
Pg.275
31
Pg.250
32
Overriding methods
Hiding methods
Pg.256-257
33
Pg.259
34
Pg.260
Pg.295
35
36
Hand out
Know inheritance
and its types. LO4
Module V:Interfaces
37
Defining Interfaces
Program on interfaces
Pg.275
Extending Interfaces
Pg.276
Explicit Interface
Pg.281
38
39
40
Declaration of
delegates
Program using
delegates
41
Pg.315
Pg.320
Know multicast
delegates LO6
Understand Events in
C#. LO6
Understand LINQ.
LO6
Multicast delegates
42
Events in C#
Pg.322
43
Introduction to LINQ
Hand out
Pg.352
Pg.354
47
Finally statement
Pg.360
48
Throw keyword
Hand out
49
throws keyword
Hand out
45
46
50
Understand errors.
LO7
Know Exceptions in
C#.LO7
Understand multiple
catch statements.
LO7
Pg.357
Understand finally
statement. LO7
Understand throw
keyword. LO7
Know throws
keyword.LO7
Know user defined
exception. LO7
Pg.363
Type
Internal Exam
Class test
11
Assignment (Theory)
Assignment (Practical)
Quiz
Course Reading
References
1. Programming C# 5.0: Building Windows 8, Web,
and Desktop Applications for the .NET 4.5
Framework by Ian Grififths.
2. C# 5.0 Unleashed by by Bart De Smet.
Internet Resource:
1.
2.
3.
4.
5.
www.oracle.com
www.tutorialspoint.com>Charp
Csharpbeginnerstutorial.com
https://eclipse.org
https://visualstudio.org
12
13
14
UNIT 1
C# is a simple, modern, general-purpose, object-oriented programming language developed by
Microsoft within its .NET initiative led by Anders Hejlsberg.
Features of C#
1. SIMPLE
1.
2.
3.
4.
16
Providing metadata
Enforcement of security
I/O operations
String Handling
Windows messages
Database management
Security etc.
17
4. In short, VB.NET, C# and other language compilers generate MSIL code. (In other
words, compiling translates your source code into MSIL and generates the required
metadata.)
5. Currently "Microsoft Intermediate Language" (MSIL) code is also known as
"Intermediate Language" (IL) Codeor "Common Intermediate Language" (CIL) Code.
SOURCE CODE -----.NET COMLIPER------> BYTE CODE (MSIL + META DATA)
2. Runtime process.
1. The Common Language Runtime (CLR) includes a JIT compiler for converting MSIL to
native code.
2. The JIT Compiler in CLR converts the MSIL code into native machine code that is then
executed by the OS.
3. During the runtime of a program the "Just in Time" (JIT) compiler of the Common
Language Runtime (CLR) uses the Metadata and converts Microsoft Intermediate
Language (MSIL) into native code.
BYTE CODE (MSIL + META DATA) ----- Just-In-Time (JIT) compiler------> NATIVE
CODE
Namespaces
A namespace is designed for providing a way to keep one set of names separate from another.
The class names declared in one namespace does not conflict with the same class names
declared in another.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace name
as follows:
namespacenamespace_name
{
// code declarations
}
Example
using System;
19
namespacefirst_space
{
classnamespace_cl
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
}
namespacesecond_space
{
classnamespace_cl
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
classTestClass
{
static void Main(string[] args)
{
first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_clsc = new second_space.namespace_cl();
fc.func();
sc.func();
20
Console.ReadKey();
}
}
Output Inside first_space
Inside second_space
Data types in C#
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 stores
numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the
system 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
can refer 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 builtin reference types are: object,dynamic, and string.
21
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;
Type conversion in C#
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:
Explicit type conversion - These conversions are done explicitly by users using the predefined functions. Explicit conversions require a cast operator.
}
}
}
Output 5673
C# Type Conversion Methods
C# provides the following built-in type conversion methods,some of them are:
Sr.No
ToBoolean
Converts a type to a Boolean value, where possible.
ToByte
Converts a type to a byte.
ToChar
Converts a type to a single Unicode character, where possible.
ToDateTime
Converts a type (integer or string type) to date-time structures.
ToDecimal
Converts a floating point or integer type to a decimal type.
ToDouble
Converts a type to a double type.
23
Boxing is the process of converting a value type to the type object or to any interface type
implemented by this value type. When the CLR boxes a value type, it wraps the value inside a
System.Object and stores it on the managed heap. Unboxing extracts the value type from the
object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies
the C# unified view of the type system in which a value of any type can be treated as an object.
In the following example, the integer variable i is boxed and assigned to object o.
C#
inti = 123;
// The following line boxes i.
object o = i;
The object o can then be unboxed and assigned to integer variable i:
C#
o = 123;
i = (int)o; // unboxing
Var Variable
Var is an implicit type. It aliases any type. The aliased type is determined by the C# compiler. It
makes programs shorter and easier to read. It was introduced in C# 3.0. var is used to declare
implicitly typed local variable means it tells the compiler to figure out the type of the variable at
compilation time. A var variable must be initialized at the time of declaration.Var variable can
take any type of data type
24
Console.writeLine(a);
} }
Output 3
UNIT II
Methods in C#
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:
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:
<AccessSpecifier><ReturnType><MethodName>(Parameter 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.
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.
25
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.
Passing Parameters to C#
When method with parameters is called, you need to pass the parameters to the method. There
are three ways that parameters can be passed to a method:
Mechanism
Description
Value parameters
Reference parameters
Output parameters
Arrays in C#
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.
26
Declaring Arrays
To declare an array in C#, you can use the following syntax:
datatype[]arrayName;
exampleina a[];
Initializing an Array
When the array variable is initialized, you can assign values to the array.
Example int[] a = new a[10];
Assigning Values to an Array
You can assign values to individual array elements, you can assign values to the array at the
time of declaration, as shown:
double[] balance = { 2340.0, 4523.69, 3421.0};
You can also create and initialize an array, as shown:
int [] marks = new int[5] { 99, 98, 92, 97, 95};
You may also omit the size of the array, as shown:
int [] marks = new int[] { 99, 98, 92, 97, 95};
Accessing Array Elements
Example
using System;
namespaceArrayApplication
{
classMyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */
27
inti,j;
Multidimensional Arrays
Multi-dimensional arrays are also called rectangular array. You can declare a 2-dimensional
array of strings as:
string [,] names;
or, a 3-dimensional array of int variables as:
int [ , , ] m;
Two-Dimensional Arrays
The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional
array is a list of one-dimensional arrays.
A 2-dimensional array can be thought of as a table, which has x number of rows and y number
of columns. Following is a 2-dimensional array, which contains 3 rows and 4 columns:
28
Thus, every element in the array a is identified by an element name of the form a[i , j ], where a
is the name of the array, and i and j are the subscripts that uniquely identify each element in
array a.
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row. The
Following array is with 3 rows and each row has 4 columns.
int[,] a =newint[3,4]{
{0,1,2,3},/* initializers for row indexed by 0 */
{4,5,6,7},/* initializers for row indexed by 1 */
{8,9,10,11}/* initializers for row indexed by 2 */
};
Accessing Two-Dimensional Array Elements
An element in 2-dimensional array is accessed by using the subscripts. That is, row index and
column index of the array. For example,
intval= a[2,3];
example
using System;
namespaceArrayApplication
{
classMyArray
{
static void Main(string[] args)
{
29
Where, scores is an array of two arrays of integers - scores[0] is an array of 3 integers and
scores[1] is an array of 4 integers.
Example
using System;
namespaceArrayApplication
{
classMyArray
{
static void Main(string[] args)
{
/* a jagged array of 5 array of integers*/
int[][] a = new int[][]{new int[]{0,0},new int[]{1,2},new int[]{2,4},new int[]{ 3, 6 }, new int[]{
4, 8 } };
inti, j;
31
foreach loop is similar to for loop.It is used to iterate through the items in a collection.eg:
foreach loop can be used with arrays or collections such as array list,hash tables etc.
syntaxforeach(typle variable in expression)
{
The type and variable declare the iteration variable.During execution, the iteration variable
represents the array element or collection for which an iteration is currently being performed.
in is a keyword.The expression must be an array or collection type.
Example
Using System;
Class Program
{ public static void Main()
{
numbers [0]=10;
numbers [1]=20;
numbers [2]=30;
foreach(int k in numbers)
{ console.writeLine(k);
} } }
Strings in C#
C#supports a predefined refrence data type known as string. We can use string,to declare string
type object. The System.String class also defines the properties and methods to work with string
data types.
32
Example
1. using System;
2. namespace CSharpStrings
3. {
4.
class Program
5.
{
6.
static void Main(string[] args)
7.
{
8.
string firstName = "ram";
9.
string lastName = "sham";
10.
string age = "33";
11.
string numberString = "33.23";
12.
Console.WriteLine("First Name: {0}", firstName);
13.
Console.WriteLine("Last Name: {0}", lastName);
14.
Console.WriteLine("Age: {0}", age);
15.
Console.WriteLine("Number: {0}", numberString);
16.
Console.ReadKey();
17.
}
}
}
Methods of the String Class
Some of them are :
Sr.No
Methods
33
public static string Concat(string str0, string str1, string str2, string str3)
Concatenates four string objects.
UNIT III
Member access modifiers
34
a class in a different manner. A same class may behave different type based on
constructors overloading. With one object initialization it may show simple string
message whereas in the second initialization of object with different parameter it
may done arithmetic calculation.
Example
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace Constructor_Overloading
{
class GameScore
{
string user;
int age;
//Default Constructor
public GameScore()
{
user = "Steven";
age = 28;
Console.WriteLine("Previous User {0} and he was {1} year old", user,
age);
}
//Parameterized Constructor
public GameScore(string name, int age1)
{
user = name;
age = age1;
Console.WriteLine("Current User {0} and he is {1} year old", user, age);
}
}
class Program
{
static void Main(string[] args)
{
GameScore gs = new GameScore(); //Default Constructor Called
37
Copy Constructor
A parameterized constructor that contains a parameter of same class type is called as copy
constructor. Main purpose of copy constructor is to initialize new instance to the values of an
existing instance.
38
Example
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)
{
param1 = x;
param2 = y;
}
public Sample(Sample obj) // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome", "Aspdotnet-Suresh"); // Create instance to class Sample
Sample obj1=new Sample(obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}
Destructors
Destructors are used to destruct instances of classes. When we are using destructors in C#, we
have to keep in mind the following things:
using System;
class A
{
public A()
{
Console.WriteLine("Creating A");
}
~A()
{
Console.WriteLine("Destroying A");
}
}
class B:A
{
public B()
{
Console.WriteLine("Creating B");
}
~B()
{
Console.WriteLine("Destroying B");
}
}
class C:B
{
public C()
{
Console.WriteLine("Creating C");
}
~C()
{
Console.WriteLine("Destroying C");
}
}
class App
{
publicstaticvoid Main()
{
C c=new C();
Console.WriteLine("Object Created ");
Console.WriteLine("Press enter to Destroy it");
Console.ReadLine();
c=null;
40
//GC.Collect();
Console.Read();
}
}
Properties in C#
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 useaccessors through which the values of the private
fields can be read, written or manipulated.
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:
publicstringCode
{
get
{
return code;
}
set
{
code= value;
}
}
41
get
{
return name;
}
set
{
name= value;
}
}
Object Initializer
Object initializers let you assign values to any accessible fields or properties of an object at
creation time without having to invoke a constructor followed by lines of assignment statements.
The object initializer syntax enables you to specify arguments for a constructor or omit the
arguments (and parentheses syntax). Eg: Cat cat = new Cat { Age = 10, Name = "Fluffy" };
Collection Initializer
Collection initializers let you specify one or more element initializers when you initialize a
collection class that implements IEnumerable or a class with an Add extension method. The
element initializers can be a simple value, an expression or an object initializer. By using a
collection initializer you do not have to specify multiple calls to the Add method of the class in
your source code; the compiler adds the calls.
The following examples shows two simple collection initializers:
List<int> digits = new List<int>{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
43
Partial class
With partial, you can physically separate a class into multiple files. This is often done by code
generators. When working on large projects, spreading a class over separate files allows multiple
programmers to work on it simultaneously.
Benefit of partial classes:
1) More than one developer can simultaneously write the code for the class.
2) You can easily write your code (for extended functionality) for a VS.NET generated class.
This will allow you to write the code of your own need without messing with the system
generated code.
Example
C# program that uses partial class
class Program
{
static void Main()
{
A.A1();
A.A2();
}
}
Contents of file A1.cs: C#
using System;
partial class A
{
public static void A1()
{
Console.WriteLine("A1");
}
}
Contents of file A2.cs: C#
44
using System;
partial class A
{
public static void A2()
{
Console.WriteLine("A2");
}
}
Output
A1
A2
Partial Method
A partial method has its signature defined in one part of a partial type, and its implementation
defined in another part of the type. Partial methods enable class designers to provide method
hooks, similar to event handlers, that developers may decide to implement or not. If the
developer does not supply an implementation, the compiler removes the signature at compile
time. The following conditions apply to partial methods:
Signatures in both parts of the partial type must match.
The method must return void.
No access modifiers are allowed. Partial methods are implicitly private.
Example
namespace PM
{
partial class A
{
partial void OnSomethingHappened(string s);
}
// This part can be in a separate file.
partial class A
{
// Comment out this method and the program
// will still compile.
partial void OnSomethingHappened(String s)
{
Console.WriteLine("Something happened: {0}", s); } } }
Indexers
45
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:
element-typethis[int index]
{
// The get accessor.
get
{
// return the value specified by index
}
UNIT IV
Inheritance
46
47
// Derived class
class Rectangle: Shape
{
publicintgetArea()
{
return (width * height);
}
}
classRectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
Subclass Constructor
48
This constructor is used to construct the instance variables of both the subclass and the super
class. The subclass constructor uses the keyword base to invoke the constructor method of the
super class.
Example
Hiding methods
if a method is not overriding the derived method, it is hiding it. A hiding method has to be
declared using the new keyword. The correct class definition in the second listing is thus:
using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}
class B : A
{
public new void Foo() { Console.WriteLine("B::Foo()"); }
}
class Test
{
static void Main(string[] args)
{
A a;
B b;
a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"
a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}
49
Abstract class If a class is defined as abstract then we can't create an instance of that class. By
the creation of the derived class object where an abstract class is inherit from, we can call the
method of the abstract class.
Abstract method
An Abstract method is a method without a body. The implementation of an abstract method is
done by a derived class. When the derived class inherits the abstract method from the abstract
class, it must override the abstract method. This requirement is enforced at compile time and is
also called dynamic polymorphism.
The syntax of using the abstract method is as follows:
<access-modifier>abstract<return-type>method name (parameter)
The abstract method is declared by adding the abstract modifier the method.
Sealed classes
Sealed class is used to define the inheritance level of a class.
The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is
specified as the base class of another class.
Some points to remember:
1. A class, which restricts inheritance for security reason is declared, sealed class.
2. Sealed class is the last class in the hierarchy.
3. Sealed class can be a derived class but can't be a base class.
4. A sealed class cannot also be an abstract class. Because abstract class has to provide
functionality and here we are
restricting it to inherit.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace sealed_class
{
class Program
50
{
public sealed class BaseClass
{
public void Display()
{
Console.WriteLine("This is a sealed class which can;t be further inherited");
}
}
public class Derived : BaseClass
{
// this Derived class can;t inherit BaseClass because it is sealed
}
static void Main(string[] args)
{
BaseClass obj = new BaseClass();
obj.Display();
Console.ReadLine();
}
}
}
Sealed methods -Sealed method is used to define the overriding level of a virtual method.Sealed
keyword is always used with override keyword.
Operator Overloading
Overloaded operators are functions with special names the keyword operator followed by the
symbol for the operator being defined. similar to any other function, an overloaded operator has
a return type and a parameter list.
Example of unary operator overloading
01 using System;
02 class bank
03 {
04
int x;
51
05
int y;
06
07
08
x = a;
09
y = b;
10
11
public bank()
12
13
14
15
16
17
18
Console.WriteLine();
19
20
21
22
b.x = -b.x;
23
b.y = -b.y;
24
return b;
25
26 }
27 class program
28 {
29
30
31
32
ba1.display();
33
34
ba2.display();
35
ba2 = -ba1;
36
ba2.display();
37
Console.ReadLine();
38
39 }
52
class complexNumber
05
06
int x;
07
double y;
08
09
10
x = real;
11
y = imagnary;
12
13
public complexNumber()
14
15
18
19
c.x=c1.x+c2.x;
20
c.y=c1.x-c2.y;
21
return c;
22
23
24
25
Console.Write(x);
26
Console.Write("+j"+y);
27
Console.WriteLine();
28
29
30
class Program
31
32
33
53
34
complexNumber p, q, r;
35
36
37
r = p + q;
38
Console.Write("p=");
39
p.show();
40
Console.Write("q=");
41
q.show();
42
Console.Write("r=");
43
r.show();
44
Console.ReadLine();
45
46
}
}
47 }
Operators that can be overloaded in c# as shown below:
Virtual Functions - A virtual method is the method which is declared with the
keyword virtual and it can be overridden by the derived class method by using override
keyword. When an instance method declaration includes a virtual modifier, that method is said to
be a virtual method. When no virtual modifier is present, the method is said to be a non-virtual
method.
Example
using System;
54
namespace VirtualExample
{
class Vehicle
{
public double distance=0.0;
public double hour =0.0;
public double fuel =0.0;
public Vehicle(double distance, double hour, double fuel)
{
this.distance = distance;
this.hour = hour;
this.fuel = fuel;
}
public void Average()
{
double average = 0.0;
average = distance / fuel;
Console.WriteLine("Vehicle Average is {0:0.00}", average);
}
public virtual void Speed()
{
double speed = 0.0;
speed = distance / hour;
Console.WriteLine("Vehicle Speed is {0:0.00}", speed);
}
}
class Car : Vehicle
{
public Car(double distance, double hour, double fuel)
: base(distance, hour, fuel)
{
}
public void Average()
{
double average = 0.0;
average = distance / fuel;
55
UNIT V
Interfaces
Interfaces define properties, methods, and events, which are the members of the interface.
Interfaces contain only the declaration of the members. It is the responsibility of the deriving
class to define the members. It often helps in providing a standard structure that the deriving
classes would follow.
56
Explicit interfaces in C#
C# supports a technique called explicit interface implementation which allows a method to
specify explicitly the name of the interface it is implementing.
Example
interfaceIDimensions
{
float Length();
float Width();
}
class Box : IDimensions
{
floatlengthInches;
floatwidthInches;
public Box(float length, float width)
{
lengthInches = length;
widthInches = width;
}
// Explicit interface member implementation:
floatIDimensions.Length()
{
returnlengthInches;
}
// Explicit interface member implementation:
floatIDimensions.Width()
{
returnwidthInches;
}
public static void Main()
{
Box myBox = new Box(30.0f, 20.0f);
IDimensionsmyDimensions = (IDimensions) myBox;
System.Console.WriteLine("Length: {0}", myBox.Length());
System.Console.WriteLine("Width: {0}", myBox.Width());
System.Console.WriteLine("Length: {0}", myDimensions.Length());
System.Console.WriteLine("Width: {0}", myDimensions.Width());
}
}
57
UNIT VI
Delegates
C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type
variable that holds the reference to a method. The reference can be changed at runtime.
Declaring Delegates
Delegate declaration determines the methods that can be referenced by the delegate. A delegate
can refer to a method, which has the same signature as that of the delegate.
Syntax for delegate declaration is:
delegate<return type><delegate-name><parameter list>
nstantiating Delegates
Once a delegate type is declared, a delegate object must be created with thenew keyword and be
associated with a particular method. When creating a delegate, the argument passed to
the new expression is written similar to a method call, but without the arguments to the method.
Example
usingSystem;
delegateintNumberChanger(int n);
namespaceDelegateAppl
{
classTestDelegate
{
staticintnum=10;
publicstaticintAddNum(int p)
{
num+= p;
returnnum;
58
publicstaticintMultNum(int q)
{
num*= q;
returnnum;
}
publicstaticintgetNum()
{
returnnum;
}
staticvoidMain(string[]args)
{
//create delegate instances
NumberChanger nc1 =newNumberChanger(AddNum);
NumberChanger nc2 =newNumberChanger(MultNum);
Example
usingSystem;
delegateintNumberChanger(int n);
namespaceDelegateAppl
{
classTestDelegate
{
staticintnum=10;
publicstaticintAddNum(int p)
{
num+= p;
returnnum;
}
publicstaticintMultNum(int q)
{
num*= q;
returnnum;
}
publicstaticintgetNum()
{
returnnum;
}
staticvoidMain(string[]args)
{
//create delegate instances
NumberChangernc;
60
//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}",getNum());
Console.ReadKey(); } } }
Events - Events are user actions such as key press, clicks, mouse movements, etc., or some
occurrence such as system generated notifications. Applications need to respond to events when
they occur. For example, interrupts. Events are used for inter-process communication.
Using Delegates with Events
The events are declared and raised in a class and associated with the event handlers using
delegates within the same class or some other class. The class containing the event is used to
publish the event. This is called the publisherclass. Some other class that accepts this event is
called the subscriber class. Events use the publisher-subscriber model.
Declaring Events
To declare an event inside a class, first a delegate type for the event must be declared. For
example,
publicdelegatevoidBoilerLogHandler(string status);
Next, the event itself is declared, using the event keyword:
//Defining event based on the above delegate
publiceventBoilerLogHandlerBoilerEventLog;
example
using System;
namespaceSimpleEvent
61
{
using System;
public class EventTest
{
privateint value;
public delegate void NumManipulationHandler();
public event NumManipulationHandlerChangeNum;
protected virtual void OnNumChanged()
{
if (ChangeNum != null)
{
ChangeNum();
}
else
{
Console.WriteLine("Event fired!");
}
}
publicEventTest(int n )
{
SetValue(n);
}
public void SetValue(int n)
{
if (value != n)
{
value = n;
OnNumChanged();
}
}
}
public class MainClass
{
public static void Main()
{
EventTest e = new EventTest(5);
e.SetValue(7);
e.SetValue(11);
Console.ReadKey(); } } }
LINQ in C#
62
The acronym LINQ is for Language Integrated Query. Microsofts query language is fully
integrated and offers easy data access from in-memory objects, databases, XML documents and
many more. It is through a set of extensions, LINQ ably integrate queries in C# and Visual
Basic.
Example of a LINQ query
using System;
usingSystem.Linq;
class Program
{
static void Main()
{
string[] words = {"hello", "wonderful", "LINQ", "beautiful", "world"};
//Get only short words
varshortWords = from word in words
whereword.Length<= 5
select word;
63
Example
varlongWords=words.Where( w =>w.length>10);
DimlongWords=words.Where(Function(w)w.length>10)
Types of LINQ
The types of LINQ are mentioned below in brief.
LINQ to Objects
LINQ to XML(XLINQ)
LINQ to DataSet
LINQ to Entities
Apart from the above, there is also a LINQ type named PLINQ which is Microsofts parallel
LINQ.
LINQ Architecture in .NET
LINQ has a 3-layered architecture in which the uppermost layer consists of the language
extensions and the bottom layer consists of data sources that are typically objects implementing
IEnumerable<T> or IQueryable<T> generic interfaces. The architecture is shown below in
Figure.
64
Extension Methods
Introduced with .NET 3.5, Extension methods are declared in static classes only and allow
inclusion of custom methods to objects to perform some precise query operations to extend a
class without being an actual member of that class. These can be overloaded also. Extension
methods are used to translate query expressions into traditional method calls (object-oriented).
Advantages of LINQ
LINQ offers a host of advantages and among them the foremost is its powerful expressiveness
which enables developers to express declaratively. Some of the other advantages of LINQ are
given below.
LINQ offers syntax highlighting that proves helpful to find out mistakes during design
time.
LINQ offers IntelliSense which means writing more accurate queries easily.
Writing codes is quite faster in LINQ and thus development time also gets reduced
significantly.
Viewing relationship between two tables is easy with LINQ due to its hierarchical
feature and this enables composing queries joining multiple tables in less time.
LINQ allows usage of a single LINQ syntax while querying many diverse data sources
and this is mainly because of its unitive foundation.
65
LINQ is extensible that means it is possible to use knowledge of LINQ to querying new
data source types.
LINQ offers the facility of joining several data sources in a single query as well as
breaking complex problems into a set of short queries easy to debug.
LINQ offers easy transformation for conversion of one data type to another like
transforming SQL data to XML data.
Anonymous types in C#
Anonymous types allow us to create new type without defining them. This is way to defining
read only properties into a single object without having to define type explicitly. Here Type is
generating by the compiler and it is accessible only for the current block of code. The type of
properties is also inferred by the compiler.
We can create anonymous types by using new keyword together with the object initializer.
Example
var anonymousData = new
{
ForeName = "Ram",
SurName = "Sham"
};
Console.WriteLine("First Name : " + anonymousData.ForeName);
Anonymous types are also used with the "Select" clause of LINQ query expression to return
subset of properties.
UNIT VII
Exception Handling in C#
Types of errors are : Compile time error and run time error.
66
try: A try block identifies a block of code for which particular exceptions is activated. It
is followed by one or more catch blocks.
finally: The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.
throw: A program throws an exception when a problem shows up. This is done using a
throw keyword.
Throwing our own Exceptions There may be times when we would like to throw our own
exceptions. We can do this by using the keyword throw as follows :
throw new Throwable_subclass;
example : throw new ArithmaticException();
67
Course Code:
Max. Marks: 40
Instructions:
Q. 1
1.
2.
3.
Attempt any five questions. Answer in 50 words (Recall)
[5 x 2]
Q. 2
a)
b)
c)
d)
e)
f)
g)
h)
Attempt any two questions. Answer in 200 words (Theoretical Concept)
[2 x 5 ]
a)
b)
c)
Q.3Attempt any two questions. Answer in 200 words (Practical/Application Oriented) [2 x 5]
a)
b)
c)
Q.4
Attempt any one. Answer in 600 words (Analytical Question / Case Study / Essay type
question to test analytical and Comprehensive Skill)
(10 x1]
a)
b)
68
Course Code:
Max. Marks: 40
Instructions:
1.
2.
3.
Q. 1 Attempt any five questions. Answer in 50 words (Recall)
a)
b)
c)
d)
e)
f)
g)
h)
Q. 2 Attempt any three questions. Answer in 200 words (Theoretical Concept)
[5 x 2]
[2 x 5 ]
a)
b)
c)
Q.3 Attempt any three questions. Answer in 200 words (Practical/Application Oriented) [2 x 5]
a)
b)
c)
Q.4 Attempt any two questions. Answer in 600 words (Analytical Question / Case Stud Essay
type question to test analytical and Comprehensive Skill)
(10 x1]
a)
b)
c)
69
C# Programming
Assignment-1
Class-_________________________________________________
Sem___________________________________________________
ERPID_________________________________________________
Date of submission_____________________________________
Signature of Faculty___________________________________
Assignment-1
Note: All question are compulsory.
Q-1 Explain the compilation and execution process of C# program.
Q-2 How do the value types differ from reference type?
Q-3 Explain the operators in C#.
Q-4 what is fallthrough in switch statement. How is it achieved in C#.
Q-5 Give an example where foreach loop is used.
Q-6 what are the different types of arrays. Explain jagged array with an
Example.
Q-7. What is a copy constructor? Why do we need such a constructor?
Assignment-2
Note: All question are compulsory.
Q-1 Define inheritance. What are the different types of inheritance?
Q-2 what is a property? Explain with a help of an example.
Q- 3 what is an indexer? What is it used for?
Q-4 what is hiding a method? How is it different from overriding?
Q-5 what are sealed classes and sealed methods. Give examples.
Q-6 what is explicit interface implementation? When is it used?
Q-7 what is a delegate? What is it used for? Give example.
Q-8 what is an event.
Q-9 Explain LINQ in detail.
Q-10 Explain exception handling in C#.
71