C# Unit - II
C# Unit - II
Prepared by:
UNIT II
2 Marks
1. What Is C#? (OR) How C# relates to the .NET Framework?(NOV 2013)
C# (pronounced as 'c‘ sharp') is a new computer‐programming language developed by
Microsoft Corporation, USA. C# is a fully object‐oriented language like Java and is the first
Component‐oriented language. It has been designed to support the key features of .NET
Framework, the new development platform of Microsoft for building component‐based
software solutions. It is a simple, efficient, productive and type‐safe language derived from
the popular C and C++ languages. Although it belongs to the family of C / C++, it is a purely
objected‐oriented, modem language suitable for developing Web based applications.
2. What is Characteristic of C#?
Simple
Consistent
Modern
Object - Oriented
Type - Safe
Versionable
Compatible
Interoperable
Flexible
3. What are the APPLICATIONS OF C#?
. Console applications
. Windows applications
. Developing Windows controls
. Developing ASP.NET projects
. Creating Web controls
. Providing Web services
. Developing .NET component library
4. List out the features of C++, which are dropped in C#?
The following features of C++ are missing in C#:
Macros
Multiple Inheritance
Templates
Pointers
Global Variables
typedef statement
U19CST62 - C# AND .NET PRGRAMMING 2
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Default arguments
Constant member functions or parameters
Forward declaration of classes.
5. What are the enhancements done to C++ in C# environment?
C# modernizes C++ by adding the following new features:
Automatic Garbage Collection
Versioning support
Strict type‐safety.
Properties to access data members
Delegates and events
Boxing and unboxing
Web Services.
6. List out the two types C# programs?
C# can be used to develop two categories of programs, they are,
a) Executable application programs (.exe) b) Component Libraries (.dll)
7. What are the major highlights of C#?
• It simplifies and modernizes C++
• It is the only component‐oriented language available today.
• It is the only language designed for the .NET Framework
• It combines the best features of many commonly used languages: the productivity of visual
basic, the power of C++ and the elegance of Java
• It is intrinsically object‐oriented and web‐enabled.
• It has a lean and consistent syntax.
8. List out some problems of C and C++
• They have long cycle‐time.
• They are not truly object‐oriented.
• They are not suitable for working with new web technologies.
• The have poor type‐safety.
• They are prone to costly programming errors.
• They do not support versioning.
• They are prone to memory leakages.
• They are weak in consistency
9. What is the limitation of Visual Basic?
Since Visual Basic is not truly an object‐oriented programming language, it becomes
increasingly difficult to use when systems become large.
U19CST62 - C# AND .NET PRGRAMMING 3
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Can be written as
System.Console.WriteLine
(
―Hello ECE‖
)
;
16. What are the types of tokens available in C#?
C# has five types of tokens. They are,
a) Keywords
b) Identifiers
c) Literals
d) Operators
e) Punctuators
17. What are keywords?
Keywords are an essential part of a language definition. They implement specific features of
the language. They are reserved, and cannot be used as identifiers except when they are prefaced
by the @ character. There are 79 keywords in C#. Ex: public, private, if, while etc..
18. What are identifiers?
Identifiers are programmer‐designed tokens. They are used for naming classes, methods,
variables, labels, namespaces, interfaces, etc. C# identifiers enforce the following rules:
They can have alphabets, digits and underscore characters. They must not begin with a digit
Upper case and lower case letters are distinct
Keywords in stand‐alone mode cannot be used as identifiers
C# permits the use of keywords as identifiers when they are prefixed with a ‗@‘ character.
19. What are the lexical elements of C#?
1. Comments
2. white spaces
3. tokens
4. preprocessing directives
20. What is line terminator in C#?
A new line character is known as line terminator in C#. The following characters
are treated as line terminators:
• The carriage return character (U+000D)
• The line feed character (U+000A)
• The carriage return character followed by a line feed character.
U19CST62 - C# AND .NET PRGRAMMING 5
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Classes
Interfaces
Delegates
Arrays
Predefined reference types include two data types:
Object type
String type
29. Which types of variables are initialized with default value?
The following categories of variables are automatically initialized to their default values.
Static variables
Instance variables
Array elements
30. What is the default value for built‐in data types?
All integer type 0
char type ‗\x000‘
float type 0.0f
double type 0.0d
decimal type 0.0m
bool type false
enum type 0
All reference types null
31. How constants are created in C#?
The constants can be created by using any one of the method:
usingconst keyword
Ex:constint ROW = 10;
const float PI = 3.14;
using #define statement (symbolic constants)
Ex:#define ROW 10
#define PI 3.14
32. What are the advantages of using constants?
Constants make programs easier to read and understand Easy to modify the program. They
minimize accidental errors, like attempting to assign values to some variables which are
expected to be constants.
33. Classify the C# operators.
C# operators can be classified into a number of related categories as below:
U19CST62 - C# AND .NET PRGRAMMING 8
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and decrement operators
f)Conditional operators
Bitwise operators
Special operators
34. What are special operators available in C#?
C# supports the following special operators:
is (relational operator)
as (relational operator)
typeof (type operator)
sizeof (size operator)
new (object operator)
.(dot) (member‐access operator)
checked (overflow checking)
unchecked (prevention of overflow checking)
35. What is the advantage of using foreach loop?
The advantage of foreach over for statement is that it automatically detects the
boundaries of the collection being iterated over. Further, the syntax includes a built‐in
iterator for accessing the current element in the collection.
36. What are types of parameters available?
C# employs four kinds of parameters:
Value parameters - used to pass the parameters by value
Reference parameters - used to pass the parameters by reference
Output parameters - used to pass the results back from a method
Parameter arrays (using param) - used to pass a variable number of parameters
37. Write a short note on pass by value.
By default, method parameters are passed by value. When a method is invoked,
the values of actual parameters are assigned to the corresponding formal parameters. The
value of the actual parameter that is passed by value to a method is not changed by any
changes made to the corresponding formal parameter within in the body of the method.
Ex:
using System;
U19CST62 - C# AND .NET PRGRAMMING 9
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
classPassByValue
{
staticint increment(intval)
{
return ++val;
}
public static void Main()
{
int a = 10;
Console.WriteLine(―Value of a ‐ before calling increment is ― + a);
Console.WriteLine(―Value returned by increment is ― + increment(a);
Console.WriteLine(‗Value of a - after calling increment is {0}‖, a); }
}
Output:
Value of a - before calling increment is 10
Value returned by increment is 11
Value of a - after calling increment is 10
38. Write a short note on pass by reference.
Unlike a value parameter, a reference parameter does not create a new storage
location. Instead, it represents the same storage location as the actual parameter used in the
method invocation. Remember, when a formal parameter is declared as ref, the corresponding
argument in the method invocation must also be declared as ref.
Ex:
using System;
classPassByRef
{
static void increment(ref intval)
{
++val;
}
public static void Main()
{
int a = 10;
Console.WriteLine(―Value of a ‐ before calling increment is ― + a); increment( ref a);
Console.WriteLine(‗Value of a - after calling increment is {0}‖, a);
U19CST62 - C# AND .NET PRGRAMMING 10
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
}
}
Output:
Value of a - before calling increment is 10
Value of a - after calling increment is 11
39. Write a short note on output parameters.
Output parameters are used to pass results back to the calling method. This is achieved by
declaring the parameters with an out keyword. Similar to reference parameter, an output
parameter does not create a new storage location. Instead, it becomes an alias to the parameter in
the calling method. When a formal parameter is declared as out, the corresponding actual
parameter in the calling method must also be declared as out.
Ex:
using System;
class Output
{
static void addition (int a , int b, out int result)
{
result = a + b;
}
public static void Main()
{
int x = 5, y = 8, sum;
addition(x, y, out sum);
Console.WriteLine(―The sum of {0} and {1} is {2}‖, x, y, sum);
}
}
40. Write a short note on parameter arrays (OR) params keyword (OR) variable argument
list
In C#, the methods can be defined to handle variable number of arguments using
what are known as parameter arrays. Parameter arrays are declared using the keyword params.
This can be combined with the formal parameter list and in such cases, it must be the last
parameter. It is permitted to use parameter arrays along with the value parameters, but it is not
allowed to combine the params modifier with the ref and out modifiers.
Ex:
using System;
classParamsTest
{
staticint sum(paramsint[] val)
{
int tot=0;
foreach (int i in val)
tot = tot + i;
return tot;
}
public static void Main()
{
Console.WriteLine(―The sum of 40,50,60 is {0}‖, sum(40,50,60));
Console.WriteLine(―The sum of 2,3,12,15,17 is {0}‖, sum(2,3,12,15,17));
Console.WriteLine(―The sum of 12 is {0}‖, sum(12));
}
}
Output:
The sum of 40,50,60 is 150
The sum of 2,3,12,15,17 is 49 The sum of 12 is 12
41. How the compiler selects a method for compilation?
The method selection involves following steps:
1. The compiler tries to find an exact match in which the types of actual parameters
are the same and uses that method.
2. If the exact match is not found, then the compiler tries to use the implicit conversions to the
actual arguments and then uses the method whose match is unique. If the conversion
creates multiple matches, then the compiler will generate an error message.
42. Can a method return more than one value in C#? Justify your answer.
Any method can return only one value if the return type is other than void. But in
C#, it is possible to return more than one value from the program using out parameter. For
example,
using System;
classReturnTest
{
staticint test(int a, out int b)
{
b = a + a;
return ++a;
}
public static void Main()
{
int x = 10, y;
Console.WriteLine(―The value of x is {0}‖, test(x,out y));
Console.WriteLine(―The value of y is {0}‖, y);
}
}
Output:
The value of x is 11
The value of y is 20
43. What is a class?
A class is essentially a description of how to construct an object that contains fields
and methods. It provides a sort of template for an object and behaves like a basic data type
such as int. Classes provide a convenient approach for packing together a group of logically
related data items and functions that work on them.
44. Write a note on encapsulation?
Encapsulation provides the ability to hide the internal details of an object from its users. The
outside user may not be able to change the state of an object directly. However, the state of an
object may be altered indirectly using what are known accessor and mutator methods. The
concept of encapsulation is also known as data hiding or information hiding.
45. What is inheritance?
Inheritance is the concept used to build new classes using the existing class
definitions. Through inheritance a class can be modified easily. The original class is
known as base or parent class and the modified one is known as derived class or subclass or
child class. The concept of inheritance facilitates the reusuability of existing code and thus
improves the integrity of programs and productivity of programmers.
46. What is polymorphism?
Polymorphism is the ability to take more than one form. The behavior of the method depends
upon the types of data used in the operation. This is extensively used while implementing
inheritance.
}
set
{
number = value;
}
}
}
57. What are the powerful features of properties?
Other than fetching the value of a variable, a get clause uses code to calculate the value of
the property using other fields and returns the results. This means that properties are not simply
tied to data members and they can also represent dynamic data. Like methods, properties are
inheritable. The modifiers abstract, virtual, new and override may be used with them
appropriately, so the derived classes can implement their own versions of properties.
The static modifier can be used to declare properties that belong to the whole class rather
than to a specific instance of the class.
58. What are indexers?
Indexers are location indicators and are used to access class objects, just like
accessing elements in an array. They are useful in cases where a class is a container for other
objects. These are referred as ―smart arrays‖.
Ex:
publicint this [int index]
{
get
{
//return desired data
}
set
{
//set desired data
}}
59. Differentiate indexer from property.
A property can be static member, whereas an indexer is always an instance member A
get acccessor of a property corresponds to a method with no parameters, whereas a get
accessor of an indexer corresponds to a method with the same formal parameter list as
the indexer.
C# Versions
C# 1.0 – It was the first release and was included in Visual Studio.Net.
U19CST62 - C# AND .NET PRGRAMMING 21
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
C# 1.1 – It was released after the first release and Microsoft changed the Visual Studio to
Visual Studio.Net 2003 in year 2003.
C# 2.0 – It was released in year 2005 as Visual Studio 2005.
C# 3.0 – It was released with the same Visual Studio with the previous one and it was
integrated with Windows Vista and Server 2008.
C# 3.5 – AJAX – Visual Studio 2008
C# 4.0 – It was released with the Visual Studio 2010.
C# 4.5 – It was released with the Visual Studio 2012.
C# 4.5.1, 4.5.2 – It is released with Visual Studio 2013.
85. Distinguish clearly between value type and reference type in C# (Nov’15)
(Apr’16)(Nov’13)
s.no Value type Reference type
1 A Value Type holds the data within Reference Type contains a pointer to another
its own memory allocation memory location that holds the real data.
2 Value Type variables are stored in the Reference Type variables are stored in the
stack. heap
3 e.g. e.g.
int x = 10; int[] iArray = new int[20];
Here the value 10 is stored in an area In the above code the space required for the
of memory called the stack. 20 integers that make up the array is allocated
on the heap.
class Maruthi
{
public virtual void Display()
{
Console.WriteLine("Maruthi Car");
}
}
U19CST62 - C# AND .NET PRGRAMMING 22
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
class Esteem:Maruthi
{
public override void Display()
{
Console.WriteLine("Maruthi Esteem");
}
}
class Zen:Maruthi
{
public override void Display()
{
Console.WriteLine("Maruthi Zen");
}
}
class Inclusion
{
public static void Main()
{
Maruthi m=new Maruthi();
m=new Esteem();
m.Display(); // prints Maruthi Esteem
m=new Zen();
m.Display(); // prints Maruthi Zen
}
}
in inclusion polymorphism, the multiple forms occur at class level.
87. List down the various types of Inheritance (Apr’15)
Types of inheritance
Single Inheritance
Hierarchical Inheritance
Multilevel Inheritance
Multiple Inheritance
Hybrid Inheritance
89. what are the two forms of operator overloading in C#? (Nov’13)
There are three types of Overloading in C#.
1. Unary operators overloading
2. Binary operators overloading
3. Comparison operators overloading
11 Marks
1. What is meant by c# language fundamentals? (Apr’15)
To analyze the C# language fundamentals we must analyze the following.
C# Source File Structure.
C# Keywords
Identifiers.
Variable and Data types.
Variable Declaration and Initialization
Operators
Flow Controls.
I. C# SOURCE FILE STRUCTURE
DECLARATION ORDER
1. Using Statement
It is used to reference the namespaces.
Example: Using System.
2. Namespace Declaration
It is used to logically group similar classes that have related functionality. In C#
we need to declare each class in a namespace. By default namespace is
automatically created with the same name as that of the project.
2. Multi-line Comment:
Example: /*
Created on Feb 22, 2005
First C# program
U19CST62 - C# AND .NET PRGRAMMING 25
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
*/
3. Documentation Comment:
Example: ///<summary>
///</summary>
///<param> name=‖args‖ </param>
WHITESPACES
Tabs and spaces are ignored by the compiler. They are used to improve the readability of the
code.
CLASS
Every C# program includes at least one class definition. The class is the fundamental component
of all C# programs. Class is keyword.
Example: public class CSharpOne
{
……
……
……
}
A class definition contains all the variables and methods that make the program work. This is
contained in the class body indicated by the opening and closing braces.
BRACES
Braces are used for grouping statements or block of codes.
The left brace ({) indicates the beginning of a class body, which contains any variables and
methods the class needs.
The left brace also indicates the beginning of a method body.
For every left brace that opens a class or method we need a corresponding right brace (}) to close
the class or method.
A right brace always closes its nearest left brace.
MAIN () METHOD:
This line begins the Main() method. This is the line at which the program will begin executing.
Example: public static void Main(String[] args)
{
……
……
}
STRING ARGS []
III. IDENTIFIER:
An identifier is the name given by a programmer to a variable, statement label, method,
class, and interface.
- An identifier must begin with a letter.
- Subsequent characters must be letters, digits or underscore.
- An identifier must not be a C# keyword.
- Identifier must not be a C# keyword.
- Identifiers are case sensitive.
U19CST62 - C# AND .NET PRGRAMMING 27
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
- Keywords can be used as identifiers, when they are prefixed with the ‗@‘ character.
INCORRECT CORRECT
3 strikes Strikes3
Write&Print Write_Print
switch Switch
- printMe is not same as PrintMe.
IV. VARIABLE AND DATATYPES:
A Variable is a named storage location used to represent data that can be changed while
the program is running.
CONSTANT VARIABLES:
Variables whose do not change during execution of a program.
- Use the const keyword to initialize.
- Constants can be initialized using an operator.
- Constants cannot use non_const values in an expression.
CORRECT FORM INCORRECT FORM
Constint age = 21; Constint;
age = 21;
Constint m = 10; int m= 10;
Constint age = m*5; constint age = m*5;
DATATYPES:
A datatype determines the values that a variable can contain and the operations
that can be performed on it.
Categories of datatypes include:
- Value Types.
- Reference Types.
- Pointers.
VALUE DATA TYPES:
Pre defined value types are also known as simple types or primitive types.
REFERENCE DATA TYPES:
Reference Data Types represent objects. A reference serves as a handle to do the object;
it is a way to get to the object. C# reference data types are derived into two types.
- User Defined (or complex) types.
Class
Interfaces
U19CST62 - C# AND .NET PRGRAMMING 28
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Delegates
Arrays
- Pre-defined (or simple) types.
Object type
String type
V. VARIABLE DECLARATION AND INTIALIZATION:
To declare a variable with value data type.
Int age = 21;
To declare a variable with reference data type.
String name = ―Jason‖;
VALUE TYPE DECLARATION
DECLARATION:
Int age;
INTIALIZATION/ASSIGNMENT:
age = 17;
REFERENCE TYPE DECLARATION
Car mycar;
mycar = new Car (―Bumble Bee‖);
VI. OPERATORS:
Unary Operators (++, --, +, -, ~, ( ) )
Arithmetic Operators ( *, ?, %, +, -)
Shift Operators (<<, >>, >>>)
Comparison Operators (<, <=, >, >=, ==, !=)
Bitwise Operators (&, ^, |)
Logical Operators (&&, ||, !)
Conditional Operators (?, :)
Assignment Operators (=, +=, -=, *=, /=)
VII. FLOW CONTROLS:
if_else () Statement
switch () statement
while () statement
do_while () statement
for statement
foreach statement
break statement
U19CST62 - C# AND .NET PRGRAMMING 29
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
goto statement
continue statement
label statement
1. If_else statement:
if (condition) {
//statements
}
else {
//statements
}
Switch statement:
C# does not allow automatic ―fall-through‖. ―Fall-through‖ is allowed only if the
case block is empty.
For two consecutive case blocks to be executed continuously, we have to force the
process by using the goto statement.
Switch (m) { switch (m) { switch (m) {
Case 1: Case 1: Case 1:
x= y; x=y;
Case 2: Case 2: goto case 2;
x= y - m; x= y + m; Case 2:
Default: Default: x= y + m;
x= y - m; x= y - m; Default:
} } x= y - m;
}
2. While statement:
while (condition) {
//statements
}
3. for statement:
for (init; condition; exp) {
//statements
}
4. for each statement:
foreach (type variable in exp)}
//statements
U19CST62 - C# AND .NET PRGRAMMING 30
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
}
5. Break statement:
break;
6. Continue statement:
continue;
7. Label and goto statement:
Label and goto are used in combination. Labels can be used anywhere in the
program and goto is used inside loops to start a new iteration.
Gotolabelname;
Label name;
Example:
for (int i=0; i<10; i++)
{
while (x<5)
{
Y=i*x;
console.writeline (y);
If (y>10)
goto Out1;
x=x+1;
}
}
Out 1:
console.writeline (―out of loop‖);
8. Return statement:
The return branching statements is used to exit from the current method.
There are two forms:
- Return <value>;
- Return;
Example 1:
Public int sum (int x, int y) {
Return x+y;
}
Example 2:
CLASS:
A class describes in abstract all of the characteristics and behavior of a type of object.
Once instantiated, an object is generated that has all the methods, properties and other behavior
defined within the class.
PERSON
Name
Sex
Age
Tellsex ()
Tellage ()
- Public Methods
- Private Methods
PUBLIC METHODS:
Public methods are part of the class public interface. I.e. these are the methods that can be
called by other objects. To create a public method a ―public‖ keyword must be used as prefix.
Public void PressHorn ()
{
Console.writeline (―TOOT TOOT!‖);
}
Static void Main (string [] args)
{
Vehicle car = new vehicle ();
car.PressHorn ();
}
PRIVATE METHODS:
To provide for encapsulation, where the internal functionality of the class is hidden, some
methods will be defined as private. Methods with a private protection level are completely
invisible to external classes. This makes it safe for the code to be modified to change
functionality, improve performance, etc, To define a method, as private, the private keyword can
be used as a prefix to the method.
Private void MonitorOilTemperature ()
{
//Internal oil Temperature Monitoring Code…;
}
To demonstrate that this method is unavailable to external classes, try the following code
in the main method of the program. When we attempt to compile or execute the program, an
error occurs indicating that the MonitorOilTemperature method cannot be called due to its
protection level.
Static void Main (string [] args)
{
Vehicle car = new vehicle ();
car.MonitorOilTemperature ();
}
U19CST62 - C# AND .NET PRGRAMMING 34
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
FIELDS:
Fields in a class are used to hold data. Fields can be marked as public, private, protected,
internal, or protected internal. A field can optionally be declared static. A field can be declared
readonly. A readonly field can only be assigned a value during initialization or in a constructor.
A field can be given an initial value by using the assignment operator when the field is declared.
Fields should generally be private with access to fields given by using properties.
Public class car
{
Public string make =‖ford‖
}
Fields are initialized immediately before the constructor for the object instance is called, so if the
constructor assigns the value of a field, it will overwrite any value given during field declaration.
Public class car
{
Public string make = ―ford‖;
Public car ()
{
Make = ―Alfa‖;
}
}
PROPERTIES:
Adding a property to a class is similar to adding a variable.
Get
{
……….
……….
}
Set
{
……….
……….
}
}
To complete the width method, we now need to add the code that processes the getting
and setting of the properties. This is relatively simple for the get accessor. When the property
value is requested, we will simply return the value from the class-level variable.
Public int width
{
Get
{
Return width;
}
Set
{
}
}
When using the set accessor, the value that the external objects is assigning to the
property is passed as a variable named ―value‖. This can be thought of as similar to a method
parameter even though its name is hidden. For the width property, we will validate the provided
value before storing it. If the value is negative or is greater than one hundred, an exception will
be thrown and the property will remain unchanged. This is possible because of the correct usage
of the get and set accessors.
Example:
Public int width
{
Get
{
Return width;
}
Set
{
If(value<0||value >100)
{
Throw new overflowException ();
}
Width value;
}}
Public int height
{
Get
{
Return height
}
USING PROPERTIES:
Properties of instantiated objects are accessed using the object name followed by the member
access operator (.) and the property name. The property can be read from and written to using
similar syntax as for a standard variable.
Example:
Static void main (String [] args)
{
Rectangle rect = new Rectangle ();
rect.Width =50;
rect.Height = 25;
Rectangle Square = new Rectangle ();
square.Height = square.Width = 40;
Console.WriteLine (rect.Height); //Output:‖25‖
Console.WriteLine (square.Width); //Output:‖40‖
rect.Height = 125;
}
READ ONLY PROPERTIES:
Example:
Public int Area
{
Get
{
return height*width;
}
}
Public int Perimeter
{
Get
{
return 2*(height + width);
}
}
4. Explain Inheritance in C#
Inheritance is the ability to derive new classes from existing ones. A derived class (―sub class‖)
inherits the instance variables and method of the base class (―parent class‖), and may add new
instance variables and methods. Inheritance defines a hierarchical relationship among classes
wherein one class shares the attributes and method defined in one or more classes.
Types of inheritance
Single Inheritance
Hierarchical Inheritance
Multilevel Inheritance
Multiple Inheritance
Hybrid Inheritance
Examples For various types of inheritance
Single Inheritance
Example: Animal
Dog
Hierarchical Inheritance
Example:
Animal
Multiple Inheritance
Example: Horse Donkey
Mule
Multilevel Inheritance
Example: Animal
Dog
Bull Dog
Hybrid Inheritance
It is a combination of all the above types of Inheritance
Example: Animal
Mammal Reptile
Frog Snake
Note: C# does not directly support Multiple Inheritance. This concept is implemented using
Interfaces.
Rules of Inheritance:
A class can only inherit from one class (known as single Inheritance)
A subclass is guaranteed to do everything the base class can do.
A subclass inherits members from its class and can modify or add to its behavior and
properties.
A subclass can define members of the same name in the base class, thus hiding the base
class members.
Inheritance is transitive (i.e., class A inherits from class B, including what B inherited
from class C).
U19CST62 - C# AND .NET PRGRAMMING 39
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
All class inherits from the highest object class in the inheritance hierarchy.
Private members and constructors are not inherited by subclasses.
Example for Inheritance:
Class BirthdayParty: HappyBirthday
{
Public BirthParty ( ): base ( )
{
}
Public string get party (boolhaveParty)
{
if (have Party ==true)
{
return ―Enjoy your Party!‖;
}
else
}
return ―Sorry- no party for you!‖;}} }
Use the abstract modifier in a method or property declaration to indicate that the method
or property does not contain implementation. Abstract method declarations are only
permitted in abstract classes.
Example for abstract classes:
Using system;
Using system.Collection.Generic;
Using system.Ling;
Using system.Text;
Namespace console application 6
{
Abstract public class Bank Account
{
Abstract public void withdrawal (double dwithdrawal);
}
Public class savings Account: BankAccount
{
Override public void withdrawal (double dwithdrawal);
{
Console.WriteLine (―Call to saving Account.withdrawal ( ) {0}‖,
dwithdrawal);
}
}
Public class checking Account: BankAccount
{
Override public void withdrawal (double dwithdrawal)
{
Console.WriteLine (―call to checking Account.dwithdrawal ( ) {0}‖,
dwithdrawal);
}
}
Class program
{
Static void main (string [ ] args)
{
SavingsAccountsa =new SavingsAccount ( );
Sa.withdrawal (1000);
CheckingAccountca = new CheckingAccount ( );
ca.withdrawal (2000);
Console.ReadLine ( );
}
}
}
Snippet:
Using system;
// Abstract class
Abstract class MyBaseC
{
Protected int x= 100;
Protected int y= 150;
// Abstract method
Public abstract void
MyMethod ( );
// Abstract Property
Public abstract int Get x
{
Get;
}
}
Class MyDerivedc: MyBaseC
{
Public override void MyMethod ( )
{
X++;
}
// overriding property
Public override int Get x
{
Get
{
Return x+10;
}
}
Public static void main ( )
{
MyDerivedC mc = new MyDerivedC ( );
mc.MyMethod ( );
Console.WriteLine (―x= {0}‖, mc.Get x);
}
}
Get
{
Return balance;
}
Set
{
Balance = value;
}
}
Public abstract void PrintAccountInfo ();
}
Public class Savings: AccountInfo, BankOperations
{
Public void withdraw (double amount)
{
Balance = Balance-amount;
}
Public void Deposit (double amount)
{
Balance = Balance + amount;
}
Public double BalanceInquiry ()
{
Return Balance;
}
Public void PrintAccountInfo ()
{
Console.Writeline (―Account Balance: ― +Balance);
}}
Public interface BankOperations
{
Public void Withdraw (double amount);
Public void Deposit (double amount);
Public double BalanceInquiry ();
}
RESULT:
Account Balance: 500.0
Updated Balance: 750.0
ABSTRACT CLASS VS INTERFACE
An Interface is useful because any class can implement it. But an interface, compared to
an abstract class, is like a pure API specification and contains no implementation.
If another method is added in an Interface, all classes that implement, that interface will
be broken.
A good Implementation of both is to create an interface and let the abstract class
implement it. So when there is a need for adding methods, it can be safely added to the
abstract class itself rather than the Interface.
Use Interfaces when a certain method needs to be forcibly overridden/enforced by a class.
METHOD OVERLOADING:
Static Polymorphism is also called as Method overloading.
Method Overloading is the process of declaring methods with the same name but
different parameter types.
Multiple methods are permitted in a class provided their signatures are unique.
A method can be overloaded in the same class or in a sub class.
Which overloaded method to call is based on reference type and decided at compile time.
Method Overloading is also known as Compile Time Polymorphism.
RULES FOR METHOD OVERLOADING:
Overloaded methods must change the arguments list.
Overloaded methods can change the return type.
Overloaded methods can change the access modifiers.
Overloaded methods can declare new or broader checked exceptions.
Example for Method Overloading:
Using System;
Namespace ProgramCall
{
Class class1
{
Public int Sum (intA, int B)
{
Return A+B;
}
Public float Sum (intA, float B)
{
Return A+B;
}
Class class2: class1
{
Public int Sum ()int A, int B, int C)
{
Return A+B+C;
}}
Class Mainclass
{
U19CST62 - C# AND .NET PRGRAMMING 46
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
OUTPUT:
Area of Square = 27.04
Area of Cube = 162.24
OVERLOADING VS OVERRIDING
CRITERIA OVERLOADED METHOD OVERRIDING METHOD
Argument List Different Same
Return Type Can Change Same
Access level Can Change Cannot be narrower
Invocation Based on reference type and Based on object type and
decided at Compile Time decided at Run Time.
An Array is a data structure that contains a number of variables, which are accessed
through computed indices.
The variables contained in an array, are called the elements of the array.
They must all be of the same type, and this type is called the element type of the array.
SYNTAX:int [ ] numbers;
Array on Heap:
A one-dimensional array on the heap.
int [ ] = numbers;
numbers = new int[4];
There are three steps to create an array.
1. Declaration
2. Construction/ Creation
3. Initialization
Example:
Public class ArrayTest
{
Public Static void main (String [ ] args)
{
int [ ] scores;
scores = new int [3];
scores [0] = 10;
scores [1] = 7;
scores [2] = 9;
U19CST62 - C# AND .NET PRGRAMMING 49
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
}}
Creating an Array Declaration:
Declaring an array means providing a name and it‘s Data Type.
1. Single Declaration
2. Multiple Declaration
3. Array of Objects
Example:
Public class ArrayTest
{
Public static void Main (String [ ] args)
{
int [ ] numbers;
char [ ] letters, symbols;
string [ ] countries;
}}
MANIPULATING ARRAYS:
Example:
Public class ArrayTest
{
Public static void Main (string [ ] args)
{
int [ ] numbers = new int [3];
numbers [0] =100;
numbers [1] =200;
numbers [2] =300;
int [ ] new Numbers = {1,2,3};
for (int i=0; i<numbers.Length; i++)
{
System.Console.WriteLine (numbers [i]);
}
numbers = new Numbers;
Sum Numbers (numbers);
Sum Number (new int [ ] {3,2,1});
}
Static void sumNumbers (int [ ] n)
{
Int sum = 0;
For (int i=0; i<n.Length; i++)
Sum+ = n[i];
System.Console.WriteLine (Sum);
}}
Single – Dimensional Arrays are declared as
int [ ] numbers;
numbers = new int [4];
string [ ] myStringArray;
can also be initialized as,
int [ ] numbers = new int [ ] {1,3,5,7,9};
string [ ] mystringArray = new string [ ]
{―Sun‖, ―Sat‖, ―Mon‖, ―Tues‖, ―Wed‖, ‖Fri‖ };
int [ ] numbers = {1,3,5,7,9};
string [ ] mystringArray = {―Sun‖, ―Sat‖, ―Mon‖, ―Tues‖, ―Wed‖, ―Fri‖};
Multi Dimensional Arrays are declared as
int [,] numbers;
numbers = new int [4,2];
int [, , ] numbers;
Example:
Console.WriteLine (―Single Dimension Array Sample‖);
//single dim array
String [ ] strArray = new string [ ] {―Mahesh Chand‖, ―Mike Gold‖, ―Raj
Beniwal‖, ―Praveen Kumar‖, ―DhineshBeniwal‖};
//Read array items using foreach loop
foreach (string str in strArray)
{
Console.WriteLine (―Multi – Dimension Array Sample‖);
String [,] string2DArray = new string [2,2] { {―Rosy‖, ―Amy‖}, {―Peter‖,
―Albert‖}};
foreach (string str in String2DArray)
{
Console.WriteLine (str);
}
Console.WriteLine (―……‖);
Console.WriteLine (―Jagged Array Sample‖);
U19CST62 - C# AND .NET PRGRAMMING 52
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
int [ ] [ ] int Jagged Array S ={ new int [ ] {2,12}, new int [ ] {14, 14, 24, 34},
new int [ ] {6,16,26,36,46,56}};
//Loop through all items of a jagged array
for (int i=0; i<int JaggedArray3.Length; i++)
{
Console.Write (―Element ({0}:‖,i);
for (int j=0; j<int JaggedArray3[i].Length; j++)
{
Console.Write (―{0}{1}‖, int JaggedArray3 [i][j], j==(int
JaggedArray3[i].Length-1)?‖‖:‖‖);
}
Console.WriteLine ();
}
Console.WriteLine (―………‖);
OUTPUT:
Single Dimension Array Sample
Mahesh Chand
Mike Gold
Raj Beniwal
Praveen Kumar
Dinesh Beniwal
----------------------------------------------------------
Multi – Dimension Array Sample
Rosy
Amy
Peter
Albert
----------------------------------------------------------
Jagged Array Sample
Element (0): 2 12
Element (1): 14 14 24 34
Element (2): 6 16 26 36 46 56
----------------------------------------------------------
9. Explain Structs In Detail. (Apr 2012)
U19CST62 - C# AND .NET PRGRAMMING 53
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Structures (Struct) are similar to classes. Are used for simple composite data types.Struct
keyword is used to declare structures.
Syntax:
StructStruct_name
{
data member1;
data member2;
………..
………..
………..
}
Variables are known as members or fields or elements.
Example:
Struct student
{
Public string Name;
Public intRollNumber;
Public double TotalMarks;
}
Student S1 //declare a student
S1.Name = ―John‖
S1.RollNumber = ―0200789‖
S1 is a variable type of structure student. Member variable can be accessed using dot notation.
Another Example:
Using System;
Public struct Point
{
Public int x, y;
Public Point (int p1, int p2)
{
x=p1;
y=p2;
}}
Class MainClass
{
In C#, a special function called operator function is used for overloading purpose. These
special function or method must be public and static. They can take only value arguments. The
general form of an operator function is as follows.
Public static return-type operator op (argument list)
Where ‗op‘ is the operator to be overloaded and operator is the required keyword. For
overloading the unary operators, there is only one argument and for overloading a binary
operator there are two arguments. We must remember that at least one of the arguments must be
a user-defined type such as class or struct type.
Example for Operator Overloading:
Using System;
Class Complex
{
Private int x;
Private int y;
}
Public complex (int i, int j)
{
x=i;
y=j;
}
Public void show xy ()
{
Console.WriteLine (―{0}{1}‖, x, y);
}
Public static complex operator + (complex c1, complex c2)
U19CST62 - C# AND .NET PRGRAMMING 56
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
{
Complex temp = new Complex ();
temp.x = c1.x + c2.x;
temp.y = c1.y + c2.y;
return temp;
}}
Class Myclient
{
Public static void Main ()
{
Complex c1 = new Complex (10, 20);
c1.showxy (); //displays 10 &20
Complex c2 = new Complex (20,30);
c2.Showxy (); //displays 20 & 30
Complex c3 = new Complex ();
c3 =c1 + c2;
c3.showxy (); // displays 30 & 50
}}
When a binary arithmetic operator is overloaded, corresponding assignment operators
also get overloaded automatically. For example if we overload + operator, it implicitly overloads
the += operator also.
Overloading Equality Operators:
Using System;
Class Complex
{
Private int x;
Private int y;
{
}
Public Complex (int I, int j)
{
x=i;
y=j;
}
Public void show xy ()
{
Console.WriteLine (―{0} {1}‖, x, y);
}
Public override bool Equals (object 0)
{
If ((complex) 0.x == this.x&& (complex) 0.y = = this.y)
return true;
else
return false;
}
Public override intGetHashCode ()
{
returnthis.ToString (). GetHashCode ();
}
Class Myclient
{
Public static void Main ()
{
Complex c1 = new Complex (10,20);
c1.showxy (); //displays 10 & 20
Complex c2 = new Complex (10, 20);
c2.showxy (); //displays 10 & 20
Complex c3 = c2;
c3.showxy (); //displays 10 & 20
if (c1.Equals (c2))
Console.WriteLine (―OK‖);
Else
Console.WriteLine (―NOT OK‖);
If (c2.Equals (c3))
Console.WriteLine (―OK1‖);
}}
{
Private string [ ] range = new string [5];
Public string this [ intindexrange]
{
Get
{
Return range [ indexrange];
}
Set
{
Range [indexrange] = value;
}}}
Class ChildClass
{
Public static void Main ()
{
ParentClassobj = new ParentClass ();
obj [0] =‖ONE‖;
obj [1] =‖TWO‖;
obj [2] =‖THREE‖;
obj [3] =‖FOUR‖;
obj [4] =‖FIVE‖;
Console.WriteLine (―Welcome to C# Home Page/n‖);
Console.WriteLine (―\n‖);
Console.WriteLine (―{0}\n, {1}\n, {2}\n, {3}\n, {4}\n‖, obj [0], obj [1],
obj [2], obj [3], obj [4]);
Console.WriteLine ();
Console.ReadLine ();
}}}
The C# collection classes are a set classes designed specifically for grouping together
objects and performing tasks on them. A number of collection classes are available with C# and
we will be looking at the key classes that are available.
Creating C# List Collection – List <T> and ArrayList
Both the List <T> and ArrayList classes have properties very similar to C# Arrays. One
key advantage of these classes over arrays is that they can grow and shrink as the number of
stored objects changes.
The List <T> class is contained with the System.Collections.Generic namespaces while
the ArrayList class is contained within the System.Collections namespace.
The syntax for creating a List <T> Collection is as follows.
List <type> name = new List <type> ();
An ArrayList object is created in a similar manner, although without the type argument.
ArrayList name = new ArrayList ();
With the above syntax in mind we can now create a List <T> object called ColorList.
Using System;
Using System.Collections.Generic;
Public class Lists
{
Static void Main ()
{
List <string>colorlist = new List <string> ();
}}
Adding Items to Items:
Once a List object has been created there are a number of methods which may be called to
perform tasks on the List. One such method is the Add () method which, as the name suggests, is
used to add items to the List Object.
List <String>colorlist = new List <string> ();
colorlist.Add (―Red‖);
colorlist.Add(―Green‖);
colorlist.Add(―Yellow‖);
colorlist.Add(―Purple‖);
colorlist.Add(―Orange‖);
Accessing List Items:
Individual items in a list may be accessed using the index value of the item (keeping in mind that
the first item is index 0, the second index 1 and so on). The index value is placed in square
brackets after the list name. For example, to access the second item in the colorlist object.
Console.WriteLine (colorlist[1]);
A list item value can similarly be changed using the index combined with the assignment
operator. For example, to change the color from Yellow to Indigo,
Colorlist [2] =‖Indigo‖;
All the items in a list may be accesses using a foreach loop. For example:
foreach (string color in colorlist)
{
Console.WriteLine (color);
}
When compiled and executed, the above code will output each of the color strings in the color
strings in the colorlist objects:
Colorlist.Remove (―red‖);
It is important to note that items in a List may be duplicated. In the case of duplicated items, the
Remove () method will only Remove the first matching instances.
Inserting Items into a C# List:
Previously we used the Add () method to add items to a list. The add () method, however, only
adds items to the end of a list. Sometimes it is necessary to insert a new item at a specific
location in a list. The Insert () method is provided for this specific purpose. Insert () takes two
arguments, an integer indicating the index location of the insertion and the index location of the
insertion and the item to be inserted at that location 2 in our example list.
Colorlist.Insert (2, ―white‖);
Sorting Lists in C#:
There is no way to tell C# to automatically sort a list as items are added. If the items in a list are
required to be always sorted into order the sort () method should be called after new times are
added.
Colorlist.Sort ();
Finding Items in a C# List or ArrayList
A number of methods are provided with the List and ArrayList classes for the purpose of
finding items. The most basic method is the contains () method, which when called on a List or
ArrayList object returns true if the specified item is found in the list, or false if it is
not.Theindexof () method returns the index value of a matching item in a List. For example, the
following code sample will output the value 2, which is the index position of the ―Yellow‖
string.
List <string>colorlist = new List <string> ();
colorlist.Add(―Red‖);
colorlist.Add(―Green‖);
colorlist.Add(―Yellow‖);
colorlist.Add(―Purple‖);
colorlist.Add(―Orange‖);
Console.WriteLine (colorlist.Indexof (―Yellow‖));
If the item is not found in the List a value of -1 is returned by the Indexof () method. This
technique could be used to replace a specific value with another. For example, without knowing
in advance the index value of the ―Yellow‖ string we can change to ―Black‖.
Colorlist [colorlist.Indexof(―Yellow‖)] = ―Black‖;
The LastIndexof () method returns the index value of the last item in the list to match the
specified item. This is particularly useful when a list contains duplicate items.
Obtaining Information About a List:
There are two class members that are useful for obtaining information about a C# List or
ArrayList collections object. The capacity property can be used to identify how many
items a collection can store without having to resize.
The count property, on the other hand, identifies how many items are currently stored in
the list. Capacity will always exceed count.
In instance where a large gap exists between count and capacity the excess capacity may
be removed with a call the TrimExcess () method.
Clearing and Triming C# Lists:
All the items in a list may be removed using the clear () method.
Colorlist.Clear ();
The Clear () method removes the items from the list and sets the Count property to zero. The
capacity property, however, remains unchanged. To remove the capacity of a list follow the
Clear () method call with a call to TrimExcess ().
13. Explain Strings In Detail.
The .NET Framework System.String class represents an immutable string of characters.
Immutable because its value can‘t be modified once it‘s been created. Methods that appear to
modify a string actually return a new string containing the modification. Besides the string class,
the .NET Framework classes offer String Builder, String Format, String Collection, and so on,
Recall that all data types both predefined and user defined inherit from the system.object
class in the .NET Framework, which is aliased as object.
Public class thing
{
Public int i=2;
Public int j=3;
}
Public class objecttypeapp
{
Public static void Main ()
{
object a;
a=1;
Console.WriteLine (a);
Console.WriteLine (a.ToString ());
Console.WriteLine (a.Gettype ());
Console.WriteLine ();
Thing b = new Thing ():
Console.WriteLine (b);
Console.WriteLine (b.ToString ());
Console.WriteLine (b.Gettype ());
}}
OUTPUT:
1
1
System.Int32
ObjectType.Thing
ObjectType.Thing
ObjectType.Thing
Numeric String Parsing:
All the basic types have tostring method, which is inherited from the object type, and all
the numeric types have a parse method, which takes the string representation of a number and
returns you its equivalent numeric value.
Public class NumParsingApp
{
Public static void Main (string [ ] args)
{
int i = int.parse (―12345‖);
Console.WriteLine (―i={0}‖,i);
int j = Int32.Parse (―12345‖);
Console.WriteLine (―j= {0}‖, j);
double d = double.Parse (―1.2345E +6‖);
Console.WriteLine (―d ={0:F}‖, d);
String s = i.ToString ():
Console.WriteLine (―S = {0}‖, S);
}}
OUTPUT:
i=12345
j=12345
d=1234500.00
s=12345
Strings and Date Time:
A date time object has a property named ticks that stores the date and time as the number of 100
– nanosecond intervals.
Date and Time values are formatted using standard or custom patterns stored in the properties of
a Date Time Format Info Instance.
Encoded Strings:
The System text namespace offers an Encoding class. Encoding is an abstract class, so we
can‘t instantiate it directly. It does provide a range of methods and properties for converting
arrays and strings of Unicode characters to and from arrays of bytes encoded for a target code
page.
The String Builder Class:
With the String class, methods that appear to modify a string actually return a new string
containing the modifications. This behavior is sometimes a nuisance because if you make several
modifications to a string, we need to end up working with several generations of copies of the
original. For this reason, string Builder class in the System.Text namespace is provided.
Splitting String:
The string class offers a split method, for splitting a string into sub strings, with the splits
determined by arbitrary separator characters that you supply to the method.
Class SplitstringsApp
{
Static void Main (String [ ] args)
{
String s =‖Once upon A Time In America‖);
Char [ ] seps = new char [ ] { ‗ ‗};
Foreach (string ss in s.Split (seps))
Console.WriteLine (ss);
}}
OUTPUT:
Once
Upon
A
Time
In
America
Extending Strings:
In libraries before the .NET era, it became common practice to extend the string class
found in the library with enhanced features. Unfortunately, the string class in the .NET
Framework is sealed, therefore, you can‘t derive from it. On the other hand, its entirely possible
to provide a series of encapsulated static methods that process strings.
Example:
The string class offers the TOUPPER and TOLOWER methods for converting to
uppercase or lowercase, respectively but this class does not offer a method to convert to proper
case (i.e.) Initial capitals on each word.
String Interning:
During the process of string interning, all the constant strings in an application are stored in a
common place in memory, thus eliminating unnecessary duplicates. This practice clearly saves
space at run time but can confuse the unwary.
EXPRESSION MEANINGS
Matches any characters except \n
[characters] Matches a single character in the list.
[^characters] Matches a single character not in the list.
[char X – char Y] Matches a single character in the specified range.
\w Matches a word character
\W Matches a non-word character
\s Matches a white space character
\S Matches a non-white character.
Class splitRegExApp
{
Static void Main (string [ ] args)
{
String S = ―Once upon A Time in America‖;
Char [ ] seps = new char [ ] {‗ ‗};
Regex r = new Regex (― ―);
Foreach (string ss in S.Split (S))
{
Console.WriteLine (ss);
}}}
OUTPUT:
Once
Upon
A Time
In
America
Match and Match Collection:
The System.Text namespace also offers a Match class represents the results of a regular
expression – matching operation. A match object is immutable, and the Match class has no
public constructor. In the following example, we use the Match method of the Regex class to
return an object of type Match in order to find the first Match in the input string.
Class MatchingApp
{
Static void Main (string [ ] args)
U19CST62 - C# AND .NET PRGRAMMING 69
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
{
Regex r = new Regex (―in‖);
Match m = r.Match (―Matching‖);
If (m.success)
{
Console.WriteLine (―Found ‗{0}‘ at position {1}‖, m.value, m.Index);
}}}
OUTPUT:
Found ‗in‘ at position 5.
Groups and Captures:
The System.Text namespace also offers a group class and a group collection class. The group
class represents the results from a single regular expression – matching group.
In the following example, we define three groups, ―ing‖, ―in‖, and ―n‖ and then search the string
―Matching‖ to find these patterns.
Class GroupingApp
{
Static void Main (string [ ] args)
{
Regex r = new Regex (―i(n))g‖);
Match m = r.Match (―Matching‖);
GroupCollectiongc = m.Groups;
Console.WriteLine (―Found {0} Groups‖, gc.Count);
For (int i=0; i<gc.Count; i++)
{
Group g = gc[i];
Console.WriteLine (―Found ‗{0}‘ at position {1}‖, g.Value, g.Index);
}}}
OUTPUT:
Found 3 Groups
Found ‗ing‘ at position 5
Found ‗in‘ at position 5
Found ‗n‘ at position 6
}
Public static void DisplayData (PrintDatapmethod)
{
pmethod (―This should go to the‖);
}
Public static void Main ()
{
PrintData m1delegate = new PrintData (writeconsole);
M1delegate+ = new PrintData (WriteFile);
DisplayData (m1delegate);
M1delegate- = new PrintData (WriteFile);
DisplayData (m1delegate);
}}}
EVENT:
An event is a way for a class to provide notifications to clients of that class when some
interesting things happen to an object.
Events provide a generally useful way for objects to signal state changes that may be useful to
clients of that object. Events are an important building block for creating classes that can be
reused in a large number of different programs.
Events are declared using delegates. An event is a way for a class to allow clients to give
delegates to methods that should be called when the event occurs. When the event occurs, the
delegates given to it by its clients are invoked.
Snippet:
DECLARATION
Public delegate void TimeToRise ();
Private event TimeToRiseRingAlarm ();
INSTANTIATION
RingAlarmobj = new TimeToRise (wakeup);
INVOCATION
RingAlarm ();
TimeToRise ();
Public void Wakeup ()
{
{
EventLog (Message);
}}}
Public class Attendance Logger
{
FileStreamFs;
StreamWriterSw;
Public Attendance Logger (string fn)
{
Fs = new FileStream (Fn, FileMode.Append, FileAcess.write);
Sw = new StreamWriter (Fs);
}
Public void Logger (string LogInfo)
{
Sw.WriteLine (LogInfo);
}
Public void close ()
{
Sw.Close ();
Fs.Close ();
}}
Public class RecordAttendance
{
Static void Logger (string LogInfo)
{
Console.WriteLine (LogInfo);
}
Static void Main (string [ ]args)
{
Attendance Logger F1 = new Delegate AttendanceLogger (―E:\\process.txt‖);
DelegateEvent De = new DelegateEvent ();
De.EventLog + = new DelegateEvent.AttendanceLoghandler (logger);
De.EventLog += new DelegateEvent.AttendanceLogHandler (F1.logger);
De.LogProcess ();
Console.ReadLine ();
F1.Close ();
}}}
Try
{
//statements which 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.
But in C#, both catch and finally blocks are optional. The try block can exist either with
one or more catch blocks as a finally block or with catch and finally blocks.
If there is no exception occurred inside the try block, the control directly transfers to
finally block. We can say that the statements inside the finally block is executed always.
Note that it is an error to transfer control out of a finally block by using break, continue,
return or goto.
In a C#, exceptions are nothing but objects of the type exception. The Exception is the
ultimate Base class for any exceptions in C#.
The C# itself provides couple of standard exceptions. Or even Exception class or one of
the standard derived classes of exception class like DivideByZeroException and
ArgumentException etc.
Example for Exception Handling:
Using System;
Class Myclient;
{
Public static void Main ()
{
int x=0;
int div =0;
try
{
Div =100/x;
Console.Writeline (―Not executed Line‖);
}
Catch (DivideByZeroException de)
{
Console.Writeline (―Exception Occurred‖);
}
Finally
{
Console.WriteLine (―Finally Block‖);
}
Console.WriteLine (―Result is {0}‖, div);
}}
In C#, a try block must be followed by either a catch or finally block.
Multiple Catch Block:
A try can throw multiple exceptions, which can handle by using multiple catch blocks.
We must remember that more specialized catch block should come before a generalized one.
Using System;
Class Myclient
{
U19CST62 - C# AND .NET PRGRAMMING 77
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
- System.OutofMemoryException
- System.NullReferenceException
- System.InvalidCastException
- System.ArrayTypeMismatchException
- System.IndexOutofRangeException
- System.ArithmeticException
- System.DivideByZeroException
- System.OverflowException
User – defined Exceptions:
In C#, it is possible to create our own exception class; But Exception must be the ultimate
base class for all exceptions in C#. So the user – defined exception classes must inherit from
either Exception class or one of its standard derived classes.
Example:
Using System;
Class MyException: Exception
{
Public MyException (string str)
{
Console.WriteLine (―User Defined Exception‖);
}}
Class Myclient
{
Public static void Main ()
{
Try
{
Throw new MyException (―ROSE‖);
}
Catch (Exception e)
{
Console.WriteLine (―Exception caught here‖ + e.ToString ());
}
Console.WriteLine (―Last Statement‖);
}}
C# language architect, argue that they were to some extent an experiment in Java and that
they haven't been shown to be worthwhile [1] [2].
C#'s namespaces are more similar to those in C++. Unlike Java, the namespace does not
specify the location of the source file. (Actually, it's not strictly necessary for a Java
source file location to mirror its package directory structure.)
C# includes delegates, whereas Java does not. Some argue that delegates complicate the
method invocation model, because they are handled through reflection, which is
generally slow. On the other hand, they can simplify the code by removing the need to
declare new (possibly anonymous) classes to hook to events.
Java requires that a source file name must match the only public class inside it, while C#
allows multiple public classes in the same file.
C# allows the use of pointers, which some language designers consider to be unsafe, but
certain language features try to ensure this functionality is not misused accidentally.
Pointers also greatly complicate technologies such as Java's RMI (Remote Method
Invocation), where program objects resident on one computer can be referenced within a
program running on an entirely separate computer. Some have speculated that the lack of
memory pointers in Java (substituted by the more abstract notion of object references)
was a nod towards the coming of grid computing, where a single application may be
distributed across many physical pieces of hardware.
C# supports the goto keyword. This can occasionally be useful, but the use of a more
structured method of control flow is usually recommended.
C# has true multi-dimensional arrays, as well as the array-of-arrays that is available to
Java (which C# calls jagged arrays). Multi-dimensional arrays are always rectangular (in
the 2D case, or analogous for more dimensions), whereas an array-of-arrays may store
rows (again in the 2D case) of various lengths. Rectangular arrays may speed access if
memory is a bottleneck (there is only one memory reference instead of two; this benefit is
very dependent on cache behavior) while jagged arrays save memory if it's not full but
cost (at the penalty of one pointer per row) if it is. Rectangular arrays also obviate the
need to allocate memory for each row explicitly.
Java does not include operator overloading, because abuse of operator overloading can
lead to code that is harder to understand and debug. C# allows operator overloading,
which, when used carefully, can make code terser and more readable. Java's lack of
overloading makes it somewhat unsuited for certain mathematical programs. Conversely,
.NET's numeric types do not share a common interface or superclass with
add/subtract/etc. methods, restricting the flexibility of numerical libraries.
}
public static complexNumber operator + (complexNumber c1, complexNumber c2)
{
complexNumber c = new complexNumber();
c.x=c1.x+c2.x;
c.y=c1.x-c2.y;
return c;
}
public void show()
{
Console.Write(x);
Console.Write("+j"+y);
Console.WriteLine();
}
}
class Program
{
static void Main(string[] args)
{
complexNumber p, q, r;
p = new complexNumber(10, 2.0);
q = new complexNumber(20, 15.5);
r = p + q;
Console.Write("p=");
p.show();
Console.Write("q=");
q.show();
Console.Write("r=");
r.show();
Console.ReadLine();
}
}
}
Note:-
The Method operator + () takes two argument (ComplexNumber) and add the two object in
same class.
namespaceCollectionsApplication
{
class Program
{
static void Main(string[] args)
{
string str1 = null;
string str2 = null;
str1 = "csharp";
str2 = "CSharp";
int result = 0;
result = string.Compare(str1, str2);
Console.WriteLine(result);
str1 = "CSharp";
result = string.Compare(str1, str2);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
3.stringConcat
Concat in CSharp String Class Concatenates the two specified string and create a new string.
stringconcat(string str1,string str2)
String Concat method returns a new String
Parameters:
String str1 : Parameter String
String str2 : Parameter String
Returns:
String : A new String return with str1 Concat with str2
Example:
string str1 = null;
string str2 = null;
str1 = "AHILA ";
str2 = "THANGARAJAN";
Console.WriteLine(string.Concat(str1, str2));
Console.ReadKey();
6. String Equals
This function is to check the specified two String Object values are same or not
boolstring.Equals(string str1,string str2)
Parameters:
String str1 : The String argument
String str2 : The String argument
Returns:
Boolean : Yes/No
It return the values of the two String Objects are same
For ex :
Str1 = "Equals()"
Str2 = "Equals()"
String.Equals(Str1,Str2) returns True
String.Equals(Str1.ToLower,Str2) returns False
Because the String Objects values are different
Example:
string str1 = "ANI";
string str2 = "ani";
if (string.Equals(str1, str2))
{
Console.WriteLine("Equal ");
}
else
{
Console.WriteLine("not Equal ");
}
7. string Length
The Length property in String Class returned the number of characters occurred in a String.
intstring.length
U19CST62 - C# AND .NET PRGRAMMING 87
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Returns:
Integer : The number of characters in the specified String
example:
"This is a Test".Length returns 14.
Example:
stringstr = null;
str = "ahila";
Console.WriteLine(str.Length);
11 Marks
1.a) What are the string handling methods? Describe. (NOVEMBER 2013) (Ref.Qn.No.19,
Pg.no.84)
b) Write a short note on interface properties and interface indexers. (Ref.Qn.No.6, Pg.no.43)
2.Discuss in detail about fundamental of exception handling in C#. (NOVEMBER 2013)
(Ref.Qn.No.16, Pg.no.76)
3.Write notes on the following: (APRIL 2012)
a. Access Modifiers (Ref.Qn.No.49, Pg.no.13)
b. Structs (Ref.Qn.No.9, Pg.no.54)
c. Static classes.
4. Explain Poymorphism In Detail. (Apr 2012) (Nov 2012) (Ref.Qn.No.7, Pg.no.45)
5.Discuss about Polymorphism? Give an examples. (NOVEMBER 2012) (Ref.Qn.No.7, Pg.no.45)
6.Discuss in detail Exception Handling. . (NOV2013) (NOV 2012) (Apr’14) (Ref.Qn.No.16,
Pg.no.76)
7.Discuss in detail about interfaces in .NET. (APRIL 2013) (Ref.Qn.No.6, Pg.no.43)
8.Explain in detail about properties in .NET. (APRIL 2013) (Ref.Qn.No.3, Pg.no.33)
9.Discuss different ways in which C# is different from Java (Nov’15) (Ref.Qn.No.17, Pg.no.80)