Download as pdf or txt
Download as pdf or txt
You are on page 1of 93

Unit-2

Fundamental of C#.Net
 Syntax, data types, variables, predefined data types, Flow
Control, Enum, Arrays, Preprocessor Directives, Classes,
Structures
 Fundamental of OOPs
 Inheritance
 Polymorphism
 Interface
 Array
 Events and Delegates
 Variables and Types:
 "Variables" are simply storage locations for data.
 You can place data into them and retrieve their contents as
part of a C# expression.
 The interpretation of the data in a variable is controlled
through "Types".
 C# is a "Strongly Typed" language.
 Thus all operations on variables are performed with
consideration of what the variable's "Type" is.
 There are rules that define what operations are legal in
order to maintain the integrity of the data you put in a
variable.
 The C# simple types consist of the Boolean type and three
numeric types - Integrals, Floating Point, Decimal, and String.
 The term "Integrals", which is defined in the C#
Programming Language Specification, refers to the
classification of types that include :
 sbyte, byte, short, ushort, int, uint, long, ulong, and char.
 The Boolean Type:
 Boolean types are declared using the keyword, bool. They
have two values: true or false.
 In other languages, such as C and C++, boolean conditions
can be satisfied where 0 means false and anything else
means true.
using System;

class Booleans
{
public static void Main()
{
bool content = true;
bool noContent = false;

Console.WriteLine("It is {0} that C# Station provides C#


programming language content.", content);
Console.WriteLine("The statement above is not {0}.",
noContent);
}
}
 O/p:
 It is True that C# Station provides C# programming language
content. The statement above is not False.
 Integral Types:
 In C#, an integral are whole numbers, either signed or
unsigned, and the char type.
 The char type is a Unicode character, as defined by the
Unicode Standard.
 The Range and Size of C# Integral Types, as shown in below
table..
 The Range and Size of C# Integral Types:

Type Size (in bits) Range


sbyte 8 -128 to 127
byte 8 0 to 255
short 16 -32768 to 32767
ushort 16 0 to 65535
-2147483648 to
int 32
2147483647
uint 32 0 to 4294967295
-
922337203685477580
long 64 8 to
922337203685477580
7
0 to
ulong 64 184467440737095516
15
 Floating Point and Decimal Types:
 A C# floating point type is either a float or double.
 They are used any time you need to represent a real
number.
 Decimal types should be used when representing financial
or money values.
 Table below shows the floating point and decimal types,
their size, precision, and range.
 The floating point and decimal types, their size, precision,
and range:

Type Size (in bits) precision Range

1.5 x 10-45 to 3.4


float 32 7 digits
x 1038

5.0 x 10-324 to 1.7


double 64 15-16 digits
x 10308

28-29 decimal 1.0 x 10-28 to 7.9


decimal 128
places x 1028
 The string Type:
 A string is a sequence of text characters.
 Some characters aren't printable, but you still need to use
them in strings.
 Therefore, C# has a special syntax where characters can be
escaped to represent non-printable characters.
 For example, it is common to use newlines in text, which is
represented by the '\n' char.
 The backslash, '\', represents the escape.
 When preceded by the escape character, the 'n' is no longer
interpreted as an alphabetical character, but now represents
a newline.
 Table shows a list of common escape sequences:
Escape Sequence Meaning
\' Single Quote
\" Double Quote
\\ Backslash
\0 Null, not the same as the C# null value
\a Bell
\b Backspace
\f form Feed
\n Newline
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab
 Another useful feature of C# strings is the verbatim literal, which is a string
with a @ symbol prefix, as in @"Some string".
 Verbatim literals make escape sequences translate as normal characters to
enhance readability.
 To appreciate the value of verbatim literals, consider a path statement such as
"c:\\topdir\\subdir\\subdir\\myapp.exe".
 As you can see, the backslashes are escaped, causing the string to be less
readable.
 You can improve the string with a verbatim literal, like this:
@"c:\topdir\subdir\subdir\myapp.exe".
 That is fine, but now you have the problem where quoting text is not as easy.
 In that case, you would specify double double quotes.
 For example, the string
 "copy \"c:\\source file name with spaces.txt\" c:\\newfilename.txt"
 would be written as the verbatim literal
 @"copy ""c:\source file name with spaces.txt"" c:\newfilename.txt".
 C# Operators
 Operators, their precedence, and associativity:
Category (by precedence) Operator(s) Associativity
x.y f(x) a[x] x++ x--
Primary new typeof default chec left
ked unchecked delegate
Unary + - ! ~ ++x --x (T)x right
Multiplicative * / % left
Additive + - left
Shift << >> left
Relational < > <= >= is as left
Equality == != right
Logical AND & left
Logical XOR ^ left
Logical OR | left
Conditional AND && left
Conditional OR || left
Null Coalescing ?? left
Ternary ?: right
= *= /= %= += -
Assignment right
= <<= >>= &= ^= |= =>
 Variables:
 A variable can be compared to a storage room, and is essential
for the programmer. In C#, a variable is declared like this:

<data type> <name>;

An example could look like this:

string name;

That's the most basic version. Usually, you wish to assign a


visibility to the variable, and perhaps assign a value to it at the
same time. It can be done like this:

<visibility> <data type> <name> = <value>;

And with an example: private string name = "John Doe";


 Variable names may consists of alphabets, digits
and underscore(_), subject to the following
conditions:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct. This
means that the Total is not the same as total or
TOTAL.
3. It should not be a keyword.
4. White spaces is not allowed
5. Variable names can be of any length.
 Data Types:
 Classes and Struct:
 a class is a group of related methods and variables.
 A class describes these things, and in most cases, you
create an instance of this class, now referred to as an
object.
 On this object, you use the defined methods and
variables.
 Classes and structs are essentially templates from which
you can create objects.
 Each objects can contains data and has methods to
manipulate and access that data.
 For Example,
Class PhoneCustomer
{
Public const string DayOfSendingBill = “Monday”;
Public int CustomerID;
Public string FirstName;
Public string LastName;
}
 Structs differ from classes in the way that they are stored
in memory and accessed(Classes are reference types
stored in heap; structs are value types stored on the stack),
and in some of their features(such as structs don’t support
inheritance).
 Struct syntax is similar to Classes:
Struct PhoneCustomerStruct
{
Public const string DayOfSendingBill = “Monday”;
Public int CustomerID;
Public string FirstName;
Public string LastName;
}
 For both classes and structs, you use the keyword new to
declare an instance.
PhoneCustomer myCust1 = new PhoneCustomer();
 // works for a class.
PhoneCustomerStruct myCust2 = new
PhoneCustomerStruct();
 //works for a struct.
 Class Members:
 1) Data Members. 2) Function Members
 IT actually contains data and their behavior/methods in it
and for utilization of it we need to create an object of that
particular class.
 We can create number of object with one class.
 Other Definitions of class:
1. A collection of data and code to handle that data.
2. Class is a user defined type/ abstract data type.
3. Class defines basic layout and functionality of an object.
 Data Members are those that contain the data for the
class- fields, constants and events.
 Data members can be either static or instance.
 Fields are any variables associated with the class.
 We can instantiate object like:
PhoneCustomer Cust1 = new PhoneCustomer();
Cust1.FirstName = “John”;
 Constants can be associated with classes in the same way as
variables.
 We can declare constants using const keyword.
 Function Members are those members that provides
some functionality for manipulating the data in the class.
 They include :
 methods,
 properties,
 constructors,
 finalizers,
 operators, and
 indexers.
 How Struct differ by Classes:
1. Structs are value types, not reference types.
2. Structs do not support inheritance.
3. There are some differences in the way constructors work
for structs.
In particular, the compiler always suppliers a default no-
parameter constructor, which you are not permitted to replace.
 For Example:
Class Dimensions
{
Public double Length;
Public double Width;
}
----------------------------------------
Struct Dimensions
{
Public double Length;
Public double Width;
}
Dimenstions Point = new Dimenstions();
Point.Length = 3;
Point.Width = 6;
 Clear that because structs are value types, the new keyword
does not work in the same way as it does for classes and
other reference types.
 Instead of allocating memory on the heap, the new operator
simply calls the appropriate constructor, according to the
parameters passed to it, initializing all fields.
Dimenstions Point ;
Point.Length = 3;
Point.Width = 6;
 Partial Classes:
 The partial keyword allows the class,struct, or interface to
span across multiple files.
 Typically, a class will reside entirely in a single file.
 However, in situations where multiple developers need
access to the same class, or more likely in the situation
where a code generator of some type is generating part of a
class, then having the class in multiple files can be beneficial.
 We can used simply partial keyword before class, struct or interface.
 In the following example the class TheBigClass resides in two separate
source files, BigClassPart1.cs and BigClassPart2.cs
//BigClassPart1.cs
patial class TheBigClass
{
Public void Methdone()
{
}
}
//BigClassPart2.cs
patial class TheBigClass
{
Public void MethdTwo()
{
}
}
 When project compile a single type called TheBigClass will be created
with two methods, MethodOne() and MethodTwo().
Example of Class and use of Class using C#.
using System;
{
public class UseClasses
{
public static void Main()
{
Person hs = new Person("Hitesh","Seth");
Person jd = hs;
jd.FirstName = "John";
jd.LastName = "Doe";
Console.WriteLine(hs.GetFullName());
Console.WriteLine(jd.GetFullName());
}
}
public class Person
{
private string sFirstName, sLastName;
public Person(string FirstName, string LastName)
{
this.sFirstName = FirstName;
this.sLastName = LastName;
}
public string FirstName
{
get
{
return sFirstName;
}
set
{
sFirstName = value;
}
}
public string LastName
{
get
{
return sLastName;
}
set
{
sLastName = value;
}
}
public String GetFullName()
{
return this.FirstName + "."+ this.LastName;
}
}
}
Example of Structure and use of Structure using C#.
using System;
{
public class UseStructures
{
public static void Main()
{
Person hs = new Person("Hitesh","Seth");
Person jd = hs;
jd.FirstName = "John";
jd.LastName = "Doe";
Console.WriteLine(hs.FirstName+"."+hs.LastName);
Console.WriteLine(jd.FirstName+"."+jd.LastName);
}
}
public struct Person
{
public string FirstName, LastName;
public Person(string FirstName, string LastName)
{ this.FirstName = FirstName;
this.LastName = LastName;
}
}
}
 Inheritance:
 Defining new classes from the existing one.
 The new class will get all the methods and properties of the
existing class.
 The new class known as sub class/ child class/ derived class.
 The existing class known as super class/ parent class/ base
class.
 Inheritance is implied by kind of relationship.
 Inheritance is basically used for reuse the code and focus to
make generic kind of thing rather than specific one.
 “An object can acquire the properties of another object.”
 Types of Inheritance:
 Single Inheritance: One Class inherit from another base
class is called single inheritance.
 Multiple Inheritance: Number of classes inherit from one
class is called Multiple inheritance.
 Multi-Level Inheritance: Inheritance is based on a
number of levels is called multi-level inheritance.
 Hierarchical Inheritance: This type of inheritance helps
us to create a baseless for number of classes and those
numbers of classes can have further their branches of
number of class.
 Hybrid Inheritance: In this type of inheritance, we can
have mixture of number of inheritances but this can
generate an error of using same name function from no of
classes, which will bother the compile to how to use the
functions.
 Therefore, it will generate errors in the program.
 This has known as ambiguity or duplicity.
 Inheritance Types:
C# supports two types of Inheritance mechanisms
1) Implementation Inheritance
2) Interface Inheritance
 What is Implementation Inheritance?
- When a class (type) is derived from another class(type) such
that it inherits all the members of the base type it is
Implementation Inheritance
 What is Interface Inheritance?
- When a type (class or a struct) inherits only the signatures of
the functions from another type it is Interface Inheritance
 In general Classes can be derived from another class, hence
support Implementation inheritance At the same time
Classes can also be derived from one or more interfaces
Hence they support Interface inheritance Structs can derive
from one more interface, hence support Interface
Inheritance Structs cannot be derived from another class
they are always derived from SystemValueType
 Multiple Inheritance:
 C# does not support multiple implementation inheritance
 A class cannot be derived from more than one class
However, a class can be derived from multiple interfaces
Inheritance Usage Example:
Here is a syntax example for using Implementation Inheritance
Class derivedClass : baseClass
{
}
derivedClass is derived from baseClass

Interface Inheritance example:


private Class derivedClass : baseClass , InterfaceX , InterfaceY
{
}
derivedClass is now derived from interfaces – InterfaceX, InterfaceY
Similarly a struct can be derived from any number of interfaces
private struct childStruct : InterfaceX, InterfaceY
{
}
Virtual Methods:
If a function or a property in the base class is declared as virtual it can be
overridden in any derived classes
Usage Example:
class baseClass
{
public virtual int fnCount()
{
return 10;
}
}
class derivedClass : baseClass
{
public override int fnCount()
{
return 100;
}
}
This is useful because the compiler verifies that the ‘override’ function has
the same signature as the virtual function
Hiding Methods:
Similar to the above scenario if the methods are declared in a child and
base class with the same signature but without the key words virtual and
override, the child class function is said to hide the base class function
class someBaseClass
{
}
class abcClass : someBaseClass
{
public int fnAge()
{
return 99;
}
}
class grandchildClass : abcClass
{
public int fnAge()
{
return 10;
}
}
 Sealed Classes and Methods:
 C# allows classes and methods to be declared as sealed.
 In the case of class, this means that you can’t inherit from
that class.
 In the case of methods, this means that you can’t override
that method.
Sealed class FinalClass
{
}
Class DerivedClass : FinalClass
//wrong. Compilation error.
{
}
 Inheritance Example:
using System;

namespace InheritanceApplication {
class Shape {
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}
// Derived class
class Rectangle: Shape {
public int getArea() {
return (width * height);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}
Result:
Total area: 35
Multiple Inheritance in C#
using System;

namespace InheritanceApplication {
class Shape {
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}

// Base class PaintCost


public interface PaintCost {
int getCost(int area);
}

// Derived class
class Rectangle : Shape, PaintCost {
public int getArea() {
return (width * height);
}
public int getCost(int area) {
return area * 70;
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();
int area;

Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();

// Print the area of the object.


Console.WriteLine("Total area: {0}", Rect.getArea());
Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}
Result:
Total area: 35
Total paint cost: $2450
 Polymorphism:
 Polymorphism means having more than one form.
 Overloading and overriding are used to implement
polymorphism.
 Polymorphism is classified into compile time polymorphism
or early binding or static binding and Runtime
polymorphism or late binding or dynamic binding.
 Compile time Polymorphism or Early Binding

The polymorphism in which compiler identifies which


polymorphic form it has to execute at compile time it self is
called as compile time polymorphism or early binding.

Advantage of early binding is execution will be fast.


 Because every thing about the method is known to compiler
during compilation it self and disadvantage is lack of
flexibility.

Examples of early binding are overloaded methods,


overloaded operators and overridden methods that are
called directly by using derived objects.
 Runtime Polymorphism or Late Binding

The polymorphism in which compiler identifies which


polymorphic form to execute at runtime but not at compile
time is called as runtime polymorphism or late binding.

Advantage of late binding is flexibility and disadvantage is


execution will be slow as compiler has to get the
information about the method to execute at runtime.

Example of late binding is overridden methods that are


called using base class object.
 Method Overloading in C#.NET
 The process of creating more than one method in a
class with same name or creating a method in
derived class with same name as a method in base
class is called as method overloading.

In VB.net when you are overloading a method of the base


class in derived class, then you must use the keyword
“Overloads”.

But in C# no need to use any keyword while overloading a


method either in same class or in derived class.

While overloading methods, a rule to follow is the


overloaded methods must differ either in number of
arguments they take or the data type of at least one
argument.
using System;

namespace ProgramCall
{

class Class1
{

public int Sum(int A, int B)


{
return A + B;
}

public float Sum(int A, float B)


{
return A + B;
}
}
class Class2 : Class1
{
public int Sum(int A, int B, int C)
{
return A + B + C;

}
}

class MainClass
{
static void Main()
{

Class2 obj = new Class2();

Console.WriteLine(obj.Sum(10, 20));

Console.WriteLine(obj.Sum(10, 15.70f));

Console.WriteLine(obj.Sum(10, 20, 30));

Console.Read();
}

}
}
 Method overloading provides more than one form for a
method.
 Hence it is an example for polymorphism.

 In case of method overloading, compiler identifies which


overloaded method to execute based on number of
arguments and their data types during compilation it self.
 Hence method overloading is an example for compile time
polymorphism.
 Method Overriding in C#.NET
Creating a method in derived class with same signature
as a method in base class is called as method overriding.
Same signature means methods must have same name, same
number of arguments and same type of arguments.

Method overriding is possible only in derived classes, but not


within the same class.

When derived class needs a method with same signature as in


base class, but wants to execute different code than provided
by base class then method overriding will be used.

To allow the derived class to override a method of the base


class, C# provides two options, virtual methods and abstract
methods.
using System;

namespace methodoverriding
{
class BaseClass
{
public virtual string YourCity()
{
return "New York";
}
}

class DerivedClass : BaseClass


{
public override string YourCity()
{
return "London";
}
}
class Program
{

static void Main(string[] args)


{
DerivedClass obj = new DerivedClass();
string city = obj.YourCity();
Console.WriteLine(city);
Console.Read();
}
}
}

Output

London
Example - 2 implementing abstract method
using System;
namespace methodoverridingexample
{
abstract class BaseClass
{
public abstract string YourCity();
}
class DerivedClass : BaseClass
{
//It is mandatory to implement absract method
public override string YourCity()
{
return "London";
}
private int sum(int a, int b)
{
return a + b;
}
}
class Program
{

static void Main(string[] args)


{
DerivedClass obj = new DerivedClass();
string city = obj.YourCity();
Console.WriteLine(city);
Console.Read();
}
}
}

Output

London
 Interface:
 An interface looks like a class, but has no
implementation.
 The only thing it contains are declarations of events,
indexers, methods and/or properties.
 The reason interfaces only provide declarations is because
they are inherited by classes and structs, which must provide
an implementation for each interface member declared.
 You can never instantiate an interface; it contains only the
signatures of its members.
 An interface neither constructors nor fields
 Interface definition is also not allowed to contain
operator overloads.
 It is also not permitted to declare modifiers on the
members in an interface definition.
 Interface are always implicitly “Public”, and cannot be
declared as “virtual” or “static”.
 For example:
Public interface IDisposable
{
Void Dispose();
}

Class SomeClass : IDisposable


{//This class must contain an implementation of the IDisposable .Dispose()
method, otherwise you get compilation error.
}
Public void Dispose()
{//implementation of Dispose() method
}
 Defining and Implementing Interfaces:
 Example:
Namespace ExInterface
{
Public interface IBankAccount
{
void PayIn(decimal amount);
bool Withdraw(decimal amount);
decimal Balance
{
get;
}
}
}
}
namespace ExInterface.BOBank
{
Public Class ServerAccount : IBankAccount
{
Private decimal balance;
Public void PayIn(decimal amount)
{
Balance += amount;
}

Public bool Withdraw(decimal amount)


{
If (balance >= amount)
{
balance -= amount;
return true;
}
Console.WriteLine(“Withdrawal attempt failed.”);
return false;
}
Public decimal Balance
{
Get
{
return balance;
}
}
Public override string ToString()
{
Return string.Format(“BoB server: Balance = {0,6:C}” balance);
}
}
}
 Derived Interfaces:
 It is also possible to inherit from each other in the same way
as classes do.
 Ex:
Public interface ITransferBankAccount : IBankAccount
{
bool TransferTo(IBankAccount destination, decimal amount);
}
 Array:
 Arrays in C# are much better than C++.
 Arrays are located in heap and thus are reference types.
 C# supports helper functions to iterate array elements.
 Foreach is the statement for such iteration.
 The difference between the syntax of C++ and C# array is:
1. The square brackets are placed after the type and not after
the variable name.
2. You create element locations using new operator.
 Array is a collection of elements of same data types, under a
common name.
 Types of Array:
 One Dimensional Array
 Two Dimensional Array

One Dimensional Array: If array elements are represented


by a single index (subscript) then it is known as one
dimensional array or simple array.
Datatype[] variable_name;
An array is declared by defining type of elements inside array,
followed by empty brackets and a variable name.
Initialization:
After declaration of array all the elements of array must
allocated a memory we can do this using new operator.
variable_name = new datytype[size];
Where size specifies maximum number of elements in array.

a = new int[5];

Once we allocated memory to all the elements of array, wee


need to store values inside those array elements.
Example:
int[] a = new int[3];
a[0]=10;
a[1]=20;
a[2]=30;
We can also initialize and declare array elements in one
statement.
int[] a = {10,20,30};

Accessing array elements:


After array is declared and initialized you can access array
elements using an indexer.
Array supports only integer elements as an index.
Example:
int[] a = {10,20,30};
for(int i =0; i <a.length; i++)
{
Console.WriteLine(a[i]);
}
Multi Dimensional Array:
A two dimensional array is indexed by two integer.
Declaration & Initialization:
datatype[,] variable_name = new datatype[size1,size2];
Where size1 specifies total number of rows and size2 specifies
total number of cols.
Example:
Int[,] a = new int[2,2];
Int[,] a = new {{1,4},{9,7}};

Jagged Array:
It is possible to have jagged array where rows may be different
size.
For this we need an array in which each element is another
array.
 C# supports single dimensional, multi dimensional and
jagged array(array of array).
 Examples:
int[] array a = new int[10];
// single dimensional array of int
for( int i =0; i < array)
array a[i] = i;

int[,] array2 = new int[5,10];


// 2-dimensional array of int
array2[1,2] = 5;
int[,,] array3 = new int[5,10,5];
//3-dimenstiona array of int.
array3[0,2,4] = 9;

//Jagged array- array of array of int.


int[][] arrayofarray = new int[2, ];
In Jagged array each row having different elements So, we can
declared it as Following way:
arrayofarray[0] = new int[4];
arrayofarray[1] = new int[] { 4,0,0} ;
arrayofarray[2] = new int[3];
Exceptions:
Is a runtime error.
Exception is a collection that will change normal flow of
program execution.
Exception Class:
System.Exception(global class)
 ArgumentException
 ArgumentNullException
 ArgumentOutOfRangeException
 Arithmatic Exception
 OverFlowException
 StackOverFlow Exception
 IO Exception
 FileNotFoundException
 DriveNotFoundExcption
Exception Handling:
Exception Handling using Try-Catch-Finally Statement.
Exception is a condition that will change normal flow of
program execution.
Exception are occurred in a situation like your program is
running out of memory, file does not exist in a given path, a
number divide by zero etc.
System.Exception Class
In C# Exception are represented by class.
All Exception classes must be derived from in built exception
class “Exception”.
C# execution handling use try-catch-finally keyword to
handle exception.
Syantx:

Try
{
//Statement
}
Catch(Exception ex)
{
//Step to handle error
}
Finally
{
//must be executed
}
The following step outline how this blocks to use to
handle error conditions:
1) The exception flow first entered into try block.
2) If no error occur in a try block execution proceed normally
through the block and when it reached end of try block
control will jump from try block to finally block. If error
occur within a try block, execution jump to a catch block.
3) The error condition is handled in the catch block.
4) At the end of catch block execution automatically transfer
to the finally block, if it is present.
5) The finally block is executed.

Here, Finally is optional.


There are number of catch block associated with a single try
block.
Example:
Static void Main(string[] args) Catch(DivideByZeroException ex)
{ {
Try Console.WriteLine(“We try to divide
{ number by zero”);
int[] x = new int[2]; }
x[10]=20; Catch(IndexOutofRangeException ex)
int a, b, c; {
a=10; Console.WriteLine(“Array Error”);
b=0; }
c=a/b; Catch(Exception ex)
Console.WriteLine(“C=“ +c); {
} Console.WriteLine(“Global Error”);
}
Finally
{
Console.WriteLine(“It must be Executed
”);
}
}
 Preprocessor Directives:
 Preprocessor directives are commands that are
interpreted by the compiler and affect the output or
behavior of the build process.
 Preprocessing directives are top lines in our program that
start with '#'.
 The '#' is followed by an identifier that is the directive name.
 .NET framework 1.1 and above will support these
preprocessor directives.
 Classification of C# language preprocessor directives are as
follows.
1. Conditional compilation
2. Errors , Warnings , Line & pragma
3. Region
 Classification of C# language preprocessor directives are as
follows.
1. #if , #else , #elif , #endif
2. #define and #undef
3. #warning and #error
4. #region and #endregion
5. #line
6. #pragma

 Conditional compilation: We can include and exclude


parts of the program based on the conditions.
#if , #else , #elif , #endif
#define and #undef
 Errors , Warnings , Line & pragma: The directive #error
initiates the preprocessor to rise error, #warning like #error
directive but it prompts warning to the user and continues with
the process, #line can be used to hide sections of code from the
debugger.
 The #pragma directive can either suppress or restore specific
compiler warnings.
#warning
#error
#line
#pragma
 Region: If you want to indicate a certain block of source code
with a name, you can indicate it with a name and keep the entire
block between #region and #endregion.
 So the C# code file is neatly organized as blocks, and that can be
expanded or collapsed visually.
#region
#endregion
Example:
 Directives such as #region give hints to editors for code
folding.
public class Foo
{
#region Procedures
public void IntBar(int firstParam) {}
public void StrBar(string firstParam) {}
public void BoolBar(bool firstParam) {}
#endregion
#region Constructors
public Foo() {}
public Foo(int firstParam) {}
#endregion
}
 Example-2:
//Preprocessor_if.cs
#define DEBUG
#define MYTEST
using System;
Public class MyClass
{
Static void Main()
{
#if (DEBUG && !MYTEST)
Console.WriteLine(“DEBUG is defined.”);
#elif (!DEBUG && MYTEST)
Console.WriteLine(“MYTEST is defined.”);
#elif (DEBUG && MYTEST)
Console.WriteLine(“DEBUG and MYTEST is defined.”);
#else
Console.WriteLine(“DEBUG and MYTEST is not defined.”);
#endif
}
}
 Events & Delegates:
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 publisher class. Some other
class that accepts this event is called the subscriber class.
Events use the publisher-subscriber model.
A publisher is an object that contains the definition of the
event and the delegate. The event-delegate association is also
defined in this object. A publisher class object invokes the event
and it is notified to other objects.
A subscriber is an object that accepts the event and provides
an event handler. The delegate in the publisher class invokes the
method (event handler) of the subscriber class.
 Declaring Events
To declare an event inside a class, first a delegate type for the
event must be declared.
For example,
public delegate string MyDel(string str);
Next, the event itself is declared, using the event keyword −
event MyDel MyEvent;
The preceding code defines a delegate
named BoilerLogHandler and an event named BoilerEventLog,
which invokes the delegate when it is raised.
using System;
namespace SampleApp {
public delegate string MyDel(string str);

class EventProgram {
event MyDel MyEvent;

public EventProgram() {
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username) {
return "Welcome " + username;
}
static void Main(string[] args) {
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("Tutorials Point");
Console.WriteLine(result);
}
}
}
C# - 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.
 Delegates are especially used for implementing events and the call-
back methods. All delegates are implicitly derived from
the System.Delegate class.
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.
For example, consider a delegate −
public delegate int MyDelegate (string s);
The preceding delegate can be used to reference any method that has
a single string parameter and returns an int type variable.
Syntax for delegate declaration is −
delegate <return type> <delegate-name> <parameter list>
 Instantiating Delegates
 Once a delegate type is declared, a delegate object must
be created with the new 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.
 For example −
public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
Following example demonstrates declaration, instantiation,
and use of a delegate that can be used to reference methods
that take an integer parameter and returns an integer value.
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl {

class TestDelegate {
static int num = 10;
public static int AddNum(int p) {
num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);

//calling the methods using the delegate objects


nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

Value of Num: 35
Value of Num: 175
 Multicasting of a Delegate
 Delegate objects can be composed using the "+" operator. A
composed delegate calls the two delegates it was composed
from. Only delegates of the same type can be composed.
 The "-" operator can be used to remove a component
delegate from a composed delegate.
 Using this property of delegates you can create an invocation
list of methods that will be called when a delegate is invoked.
This is called multicasting of a delegate.
 The following program demonstrates multicasting of a
delegate −
using System;

delegate int NumberChanger(int n);


namespace DelegateAppl {
class TestDelegate {
static int num = 10;

public static int AddNum(int p) {


num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);

nc = nc1;
nc += nc2;

//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
Value of Num: 75
Assignment-2 - Visual Programming

Q-1 Answer following questions: (any Five) [20]


1 Define keyword Sealed and Partial Class
with proper example.
2 Explain C# Inheritance in detail.
3 What is difference between Class and Struct?
4 Explain Method Overriding in C#.Net.
5 Explain Jagged array with proper example.
6 What is Exception? Explain in depth
Exception handling.
7 Write a note on Preprocessor directive.
8 Write a note on Garbage Collection.
Q-2 Answer the following: [10]
1 Keyword is used of specify a class that cannot inherit
by other class?
a) Sealed. b) Seal c)Lock d) Locked
2 Is there a facility of struct & class in C#?
a) True b) False
3 What is extension of a resource file?
a) .cs b) .xaml c) .resx d).rexs.
4 C# supports Multiple Inheritance.
a) True. b) False.
5 What is automatic memory management in .Net
known as?
a) Memory Allocation
b) Memory Management
c) Garbage Collection
d) Garbage Allocation.
6 What is System?
a) Namespace b) Library c) Class d) Object.
7 Default namespace in C# is_____________________________________
System. b) Program c) Library d) Application
8 The_________ directive can either suppress or restore specific
compiler warnings.
a) #pragma b)#region c)#warning d) None of
these.
9 __________ is a collection that will change normal flow of
program execution.
a) Directive b) ArrayList c) namespace d)
Exception.
10 __________ are always implicitly “Public”, and cannot be
declared as “virtual” or “static”.
a) Class b) Interface c) Structure d)
Constructor

You might also like