0% found this document useful (0 votes)
5 views90 pages

C# Unit - II

The document is a course outline for C# and .NET Programming, detailing fundamental concepts such as C# class structure, object-oriented principles, and programming constructs. It includes topics like data types, control flow, operators, and memory management, along with comparisons to other programming languages like C++ and Java. Additionally, it covers practical applications of C#, types of parameters, and programming techniques such as pass by value and pass by reference.

Uploaded by

ashwins1306
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views90 pages

C# Unit - II

The document is a course outline for C# and .NET Programming, detailing fundamental concepts such as C# class structure, object-oriented principles, and programming constructs. It includes topics like data types, control flow, operators, and memory management, along with comparisons to other programming languages like C++ and Java. Additionally, it covers practical applications of C#, types of parameters, and programming techniques such as pass by value and pass by reference.

Uploaded by

ashwins1306
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Department of Computer Science and Engineering

Subject Name: C# AND .NET PROGRAMMING Subject Code: U19CST62

Prepared by:

Dr. V. VIJAYAKUMAR, Assoc. Professor/CSE


Mrs. S. DEEBA, Asst. Prof/CSE
Mr. N. GOPINATH, Asst. Prof/CSE

Verified by: Approved by:

UNIT II

C# Fundamentals: C# Class – Object – String Formatting – Types – Scope – Constants – C#


Iteration – Control Flow – Operators – Array – String – Enumerations – Structures – Custom
Namespaces. Programming Constructs – Value Types and Reference Types – Object Oriented
Concepts – Encapsulation – Inheritance – Polymorphism – Interfaces – Collections –
Multithreading.

U19CST62 - C# AND .NET PRGRAMMING 1


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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

10. What are the limitations of using Java language?


• Java has not retained some powerful C++ features such as operator overloading.
• It also lacks inter‐operability with code developed in other languages.
11. What are important features of C#, which are adopted from other languages? (Apr’15)
C# borrows Java‘s features such as grouping of classes, interfaces and implementation
together in one file so that programmers can edit the code more easily. C# also handles objects
using references, the same way as Java. C# borrows VB‘s approach to form design, namely,
dragging controls from a tool box, dropping them onto forms, and writing event handlers for
them.
12. What is Command Line Argument?
There may be occasions when we may like our program to behave in a particular way
depending on it input provided at the time of execution. This is achieved in C# by using
what are known as command line arguments. Command line arguments are parameters
supplied to the Main method at the time of invoking it for execution.
13. What is comment? List out its types?
The statements which are not included for compilation by the compiler are called as
comments. They are used to enhance readability and understanding of code. C# permits two
types of comments, namely:
Single Line Comments
Begins with a double backslash (//) symbol. Ex: //Main method begins Multi Line Comments
This starts with /* characters and terminates with */. Ex: /* Program - Testing Delegates
Date - 09.10.08
Developer - Kumaran */
14. State the C# Program Structure.
C# program contains following sections in it:
a) Documentation Section
b) Using Directive Section
c) Interfaces Section
d) Classes Section
e) Main Method Section
15. C# is a freeform language. Comment
C# is a freeform language. So it does not care where on the line the code is begins.
Ex:
System.Console.WriteLine(―Hello ECE‖); Can be written as
System.Console.WriteLine (―Hello ECE‖);
U19CST62 - C# AND .NET PRGRAMMING 4
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

• The line separator character (U+2028)


• The paragraph separator character (U+2029)
21. What are punctuators?
Punctuators are symbols used for grouping and separating code. They define the shape
and function of a program. Punctuators or Separators in C# include:
 Parentheses ()
 Braces { }
 Brackets []
 Semicolon ;
 Colon :
 Comma ,
 Period .
22. What is stack memory and heap memory?
Stack - Represents a portion of memory that can be used by the program at runtime. This
memory is not subject to garbage collection. The lifetime of the variables stored in stack is
limited to the lifetime of the block in which it is defined. Method states are allocated on
stack. Thus, local variables, arguments of methods, and local object references are allocated
on stack memory.
Heap - This is the region of memory used for dynamic storage. It is reserved for a program to
use for the temporary storage of data structures whose existence or size cannot be determined
until the program is running. It is subjected to garbage collection. The problem of memory
leak is avoided in this type of memory allocation.
23. What is value type?
It includes simple data types such as enum, struct, char, bool, int, float, etc. Value type
variable directly contain data since memory is allocated on stack. Operation on one variable does
not affect the other value type variable. It provides efficient access and faster execution by stack
allocation.
24. What is reference type?
It includes class types, interface types, delegate types and array types. Reference variable
stores references to objects whereas the data of objects are stored in locations represented
by references. Reference variable points to an object allocated on heap. Reference variable can
have null value. One or more reference variables can be assigned with the same reference of an
object. Hence, operation on one reference variable may affect the object referenced by the
other reference variable.

U19CST62 - C# AND .NET PRGRAMMING 6


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

25. What are statements?


Statements in C# are like sentences in natural languages. A statement is an executable
combination of tokens ending with a semicolon. C# implements several types of statements.
They include:
Empty Statements
Labeled statements
Declaration statements
Expression statements
Selection statements
Interaction statements
Jump statements
The try statements
The checked statements
The unchecked statements
The lock statements
The using statements
26. What are escape sequences?
C# supports special backslash character constants that are used in output methods.
These character combinations are called as escape sequences. Some escape sequences are:
\n new line
\t horizontal tab
\f form feed
\r carriage return
\b backspace
27. What is NaN?
Floating‐point data types support a special value known as Not‐a‐Number (NaN).
NaN is used to represent the result of operations such as dividing zero by zero, where an actual
number is number is not produced. Most operations that have NaN as an operand will produce
NaN as a result.
28. List out reference data types?
The reference types can also be divided into two groups:
User‐defined (or complex) types
Predefined (or simple) types
User‐defined reference types refer to those which are defined by the user using
predefined type. They include,
U19CST62 - C# AND .NET PRGRAMMING 7
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;

U19CST62 - C# AND .NET PRGRAMMING 11


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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)
{

U19CST62 - C# AND .NET PRGRAMMING 12


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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.

U19CST62 - C# AND .NET PRGRAMMING 13


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

47. What is the Characteristic of Inheritance?


1. A derived class extends its direct base class. It can add new members to those it
inherits.However, it cannot change or remove the definition on an inherited member.
2. Constructor and destructors are not inherited. All other members, regardless of their
declared accessibility in base class, are inherited.
3. All instance of a class contains a copy of all instance fields declared in the class and its base
classes.
4. A derived class can hide an inherited member.
5. A derived class can override an inherited member.
48. Advantages of Inheritance
1. Reuse the existing code and extend the functionality.
2. Add new members to the derived class to specialize the class.
3. replace the implementation of existing methods by overriding a method that already exists in
the base class. use of virtual and override methods help to exhibit polymorphic behavior.
4. Organize software components into categories and subcategories resulting in
classification of software. Classification is the most widely accepted use of inheritance
although other mechanisms may also be used for classification.
49. List out the member access modifiers in C# (APR 2012)
private - Member is accessible only within the class containing the member.
public - Member is accessible from anywhere outside the class as well. It is also
accessible in derived classes.
protected - Member is visible only to its own class and its derived class.
internal - Member is available within the assembly or component that is being created but not to
the clients of the component.
protected internal - Available in the containing program or assembly and in the derived classes.
50. What are the features of a constructor?
The name of the constructor is the same as the class.
A constructor does not return any value and hence does not have a return type. The
formal parameters define the signature of the constructor. A constructor initializer cannot access
the object being created. A constructor is called when an object is created.
51. What is default constructor?
A public parameterless constructor is called default constructor. And it is implicitly
declared for any class. Even though there is no constructor in the class this default constructor
will be invoked and initializes the member with default value of that type.
Simply, the process called instantiation is done through calling the constructor only.

U19CST62 - C# AND .NET PRGRAMMING 14


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

52. What is the use of private constructors?


C# does not have global variables or constants. All declarations must be contained
in a class. But using static members this can be achieved some what. Such classes are
never required to instantiate objects because; object is not needed to access the static
members of a class. Creating objects for such classes may be prevented by using private
constructor to the class.
53. What is copy constructor?
A copy constructor creates an object by copying variables from another object.
But there is no copy constructor provided in C#. It should be defined by the programmer.
Ex: public Point(Point pt)
{ x = pt.x;
y = pt.y;
}
The copy constructor is invoked when instantiating the object of type Point. For example,
Point p2 = new Point(p1);
54. What is destructor?
A destructor is opposite to a constructor. It is a method called when an object is no more
required. The name of the destructor is the same as the class name and is preceded by a tilde (~).
Like constructors, a destructor has no return type.
55. What are the features of a destructor?
The name of the destructor is same as the class name. The name is preceded by ~. It is
always public. There is no parameter in the signature. There is no return type.
56. What are properties?
Properties have the same capabilities as accessor methods, but are much more elegant and
simple to use. Using a property a programmer can get access to data members easily. These are
sometimes referred as ―smart fields‖.
Ex:
classTestProp
{
privateint n;
publicint number //property defines getter and setter methods
{
get
{
return n;

U19CST62 - C# AND .NET PRGRAMMING 15


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

}
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.

U19CST62 - C# AND .NET PRGRAMMING 16


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

A set accessor of a property corresponds to a method with a single parameter named


value, whereas a set accessor of an indexer corresponds to a method with the same formal
parameter list as the indexer, plus the parameter named value. It is an error for an indexer to
declare a local variable with the same name as an indexer parameter. The indexer takes an
index argument and looks like array. The indexer is declared using the name this.
60. What is the containment inheritance?
If an object contains another object in it, it is called as containment inheritance. This
represents the ―has‐ a‖ relationship.
Ex:
class A
{
int a;
}
class B
{
int b;
A aa; // object aa is contained in object of B
….
}
61. What are the constraints on the accessibility of members and classes in C#?
1. The direct base class of a derived class must be at least as accessible as the derived class
itself.
2. Accessibility domain of a member is never larger that that of the class containing it.
3. The return type of method must be at least as accessible as the method itself.
62. What are the Characteristics of the Override?
1. An override declaration may include the abstract modifier.
2. It is an error for an override declaration to include new or static or virtual modifier.
3. The overridden base method cannot be static or nonvirtual.
4. The overridden base method cannot be a sealed method. What is the use of abstract modifier
with class?
The abstract is a modifier and when used to declare a class indicates that the class cannot
be instantiated. Only its derived classes can be instantiated. So, the object can‘t be created for an
abstract class.

U19CST62 - C# AND .NET PRGRAMMING 17


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

63. What is Regular expression?


A regular expression—also called regex, regexes, regexp, regexps, and regexen—is a
string that describes a set of strings to be found or altered according to certain syntax rules. The
regular expression pattern matching process is supported by programming languages, text
editors, and utilities. A regular expression may include alphanumeric characters,
metacharacters, and operators. Most .NET languages— including Visual C#—support regular
expressions.
64. What is polymorphism? What are the methods available to do that?
Polymorphism means ―one name, many forms‖. Essentially, polymorphism is the
capability of one object to behave in multiple ways. It can be achieved in two ways:
1. Operation Polymorphism can be achieved by using overloaded methods.
2. Inclusion Polymorphism can be achieved by using virtual methods.
65. What is operation polymorphism?
Operation polymorphism is implemented using overloaded methods and operators.
The overloaded methods are selected for invoking by matching arguments, in terms of
number, type and order. This information is known to the compiler at the time of
compilation and, therefore, the compiler is able to select and bind the appropriate method
to the object for a particular call at compile time itself. This process is called early
binding, or static binding, or static linking. It is also known as compile time
polymorphism.
66. Write a note on interface.
An interface can contain one or more methods, properties, indexers, and events
but none of them are implemented in the interface itself. It is the responsibility of the
class that implements the interface to define the code for implementation of these members.
Syntax:
interfaceInterfaceName
{
Member declarations;
}
67. What are the operators which can be overloaded?
Binary arithmetic operators +*/‐%
Unary arithmetic operators + ‐ ++ ‐‐
Binary bitwise operators & | ^ <<>>
Unary bitwise operators ~ !true false
Relational operators == != <= >= ><
U19CST62 - C# AND .NET PRGRAMMING 18
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

68. What are the operators which can’t be overloaded?


Logical operators && ||
Compound assignment operators += ‐= *= /= %=
Other operators [] () = ?: ‐> new sizeoftypeof is as
69. What are limitations of operator overloading? (NOV 2013)
1. When we overload a binary operator, its compound assignment equivalent is
implicitly overloaded.
2. Relational operators must be overloaded in pairs, i.e == and != must be done together.
3. Operators that are currently not defined in C# cannot be overloaded.
4. We cannot change the syntax, the grammatical rules that govern its use such as the number of
operands, precedence and associativity.
70. What is need for operator overloading?
1. Mathematical or physical modeling needs classes to represent objects such as
coordinates, vectors, matrices, tensors, complex numbers and so on.
2. Graphical programs where co‐ordinate related objects are used to represent positions
on the screen.
3. Financial programs where a class represents an amount of money.
4. Text manipulations where classes are used to represent strings and sentences.
71. What are the key features of Operator Overloading?
1. They must be defined as public and static
2. The retval (return value) type is the type that we get when we use this operator.
But, technically, it can be of any type.
3. The arglist is the list of arguments passed. The number of arguments will be one for
the unary operators and two for the binary operators.
4. In the case of unary operators, the argument must be the same type as that of the enclosing
class or struct.
5. In the case of binary operators, the first argument must be of the same type as that of the
enclosing class or struct and the second may be of any type.
72. Define Delegate? (APR 2012)
It is an Event handling mechanism of .NET. To raise events, a class must define one
delegate per event type. To handle events, types must implement one event handler per
event type. Delegates can reference both instance and static methods. C# uses the delegate
keyword.
73. What are steps involved in using delegates in a C# program?
1. Delegate declaration
U19CST62 - C# AND .NET PRGRAMMING 19
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

2. Delegate methods definition


3. Delegate instantiation
4. Delegate invocation
74. Write a note on delegates.
Delegate is a method which is acting for another method. A delegate declaration defines a
class using the classSystem.Delegate as a base class. Delegate methods are any functions whose
signature matches the delegate signature exactly. The delegate instance holds the reference to
delegate methods. The instance is used to invoke the methods indirectly. An important feature of
delegate is that it can be used to hold reference to a method of any class. The basic requirement
is that its signature must match the signature of the method.
75. What is an event? (Apr’16)
An event is a delegate type class member that is used by the object or class to provide a
notification to other objects that an event has occurred. The client object can act on an
event by adding an event handler to an event.
The type of an event declaration must be a delegate type and the delegate must be as
accessible as the event itself.
76. What is the difference between Read() and ReadLine()?
Read( ) - Returns a single character as int. Returns ‐1 if no more characters are available.
ReadLine() - Returns a string containing a line of text. Returns null if no more lines are
available.
77. What is an error?
Error is mistakes that can make a program go wrong. An error may produce an incorrect
output or may terminate the execution of the program abruptly or even may cause the system to
crash. There are two types of error:
1. Compiler‐time errors 2. Run‐time errors
78. Write some examples for run‐time errors.
1. Dividing an integer by zero
2. Accessing an element that is out of bounds of an array
3. Trying to store a value into an array of an incompatible class or type
4. Passing a parameter that is not in a valid range or value for a method
5. Attempting to use a negative size for an array.
79. What is Exception?
When an unplanned or unexpected event occurs, an associated exception object is
thrown. The exception will be caught by an exception handler at some level and

U19CST62 - C# AND .NET PRGRAMMING 20


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

appropriate action taken. A fatal exception—catastrophic error—is an event that cannot be


properly handled to allow the application to continue.
80. What is Exception handling?
Process of intercepting—trapping—an exception and acting appropriately in response.
81. What are tasks involved in exception handling?
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
82. Differentiate Property and Indexer
Property
A property is identified by its name
A property is accessed through the property name
A property can be static.
Indexer
An indexer is identified by its signature
An indexer element is accessed through the subscripted expression with the object name
as the array name.
Indexer is always as instance member
83. What is Override?
Supercede an instance field or virtual method in a base class with a new
definition of that member in the derived class (subclass).
84. Use a diagram and briefly discuss the evolution of C# Language (Nov’15)

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.

86. What is inclusion polymorphism? (Apr’16)


Inclusion Polymorphism is achieved through the use of virtual functions. It is known as
Runtime polymorphism, dynamic binding and late binding.
The following code snippet shows how to implement inclusion polymorphism in C#.
using System;

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

U19CST62 - C# AND .NET PRGRAMMING 23


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

88. How to declare a one-dimensional array in C# (Nov’14)


Creation of an array involves three steps.
1. Declaring the array (Declaration of Arrays).
2. Creating memory locations (Creation of Arrays).
3. Initialization of Arrays.
1 . ) Declaration of Arrays:-
Arrays are declared in C# as follows:-
Syntax:
type [ ] arrayname ;
Ex.
int [ ] num;

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

U19CST62 - C# AND .NET PRGRAMMING 24


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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.

Example: namespace CsharpSchool


3. Class Declaration
A C# source file can have several classes but only one class have the Main
method.

Example: public class CSharpOne


COMMENTS:
1. Single-line Comment:

Example: //print a message.

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 []

U19CST62 - C# AND .NET PRGRAMMING 26


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Declares a parameter named args, which is an array of string. It represents command-line


arguments.
(string[] args)
C# Statement
A complete unit of work in a C# program. A statement is always terminated with a semicolon
and may span multiple lines in our source code.
Example: (―Welcome to C#‖)
CONSOLE.WRITELINE ()
This line outputs the string, followed by a newline on the screen.
Example: Console.WriteLine (―Welcome to C#)
TERMINATING CHARACTER:
Semicolon (;) is the terminating character for any C# Statement.
II. C# KEYWORDS:
Keywords are an essential part of language definition as they implement specific features of
the language. They are reserved, and cannot be used as identifiers.
abstract as Base bool break byte case
catch char checked class const continue decimal
default delegate Do double else enum event
explicit extern False finally fixed float for
foreach goto If implicit in int interface
internal is Lock long namespace new null
object operator Out override params private protected
public readonly Ref return sbyte sealed Short
sizeof stackalloc Static struct switch this Throw
true try typeof uint ulong unchecked Unsafe
ushort using virtual volatile void while

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:

U19CST62 - C# AND .NET PRGRAMMING 31


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Public int sum (int x, int y) {


x=x+y;
if (x<100) {
return x;
} else {
return x+5;
}
}
Example 3:
Public void get sum (int x) {
System.console.writeline (x);
Return;
}

2.Explain what is an object and class


OBJECTS:(NOV 12)(Apr’16) (2 Mark)
Anything that we can describe, can be represented as an object, and that representation
can be created, manipulated and destroyed to represent how we use the real objects that it
models.
Example: Car, book, building etc;
DEFINING A OBJECT:
An object is a self-contained entity with attributes and behaviors.
Attributes: Information an object must know:
 Identity – uniqueness
 Attributes – Structure
 State – Current Condition

Behavior: Behavior an object must do:


 Methods – what it can do
 Events – what it responds to
In object-oriented programming, objects communicate and interact with each other using
messages.

U19CST62 - C# AND .NET PRGRAMMING 32


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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 ()

SYNTAX FOR CREATING CLASS:


The basic syntax for the creation of a new class is very simple. The keyword ‗class‘
followed by the name of the new class is simply added to the program. This is then followed by a
code block surrounded by brace characters { } to which the class code will be added.
Class class_name { }
Namespace classTest
{
Class vehicle
{
}
}

INSTANTIATING THE CLASS


Although we have not explicitly added any functionality to the class, it can now be instantiated
to create objects. These objects will have the standard behavior of all classes.
Static void Main (string [] args)
{
Vehicle car = new vehicle ();
}

3. Explain Methods Fields And Properties. (Apr 2013)


METHODS:(NOV 2012) (2 Mark)
There are 2 types of methods that can be created for a class.
U19CST62 - C# AND .NET PRGRAMMING 33
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

- 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.

Public int width


{
}
Once declared, functionality must be added to the property. This is achieved with the use of get
and set accessors.
Get accessor - code block that control how the property‘s value is retrieved or calculated when
requested.
Set accessor – how the properties value is validated, processed and stored when assigned a value.
The two accessors are added to the property using the get and set keywords, each with its own
code blocks.
Public int width
{

U19CST62 - C# AND .NET PRGRAMMING 35


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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
{

U19CST62 - C# AND .NET PRGRAMMING 36


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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

U19CST62 - C# AND .NET PRGRAMMING 37


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

{
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:

U19CST62 - C# AND .NET PRGRAMMING 38


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Animal

Dog Cat Cow

 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!‖;}} }

5. Explain Abstract Classes In Detail.


An abstract class is a class that provides common behavior across a set of subclasses, but it
not itself designed to have instances of its own.
- A class that indicates certain behavior but allows its subclass to provide implementation.
- A class designed only as a parent from which subclass may be derived, but which is not
itself suitable for instantiation
- A class often used to ―abstract out‖ incomplete sets of features which may then be shared
by a group of sibling sub-class which add different variations of the missing pieces.
Rules on abstract classes:
 An abstract class cannot be instantiated and an abstract class may contain abstract
methods and properties.
 A class with at least one abstract method must be declared as an abstract class.
 A non abstract class derived from an abstract class must include actual implementations
of all inherited abstract methods and properties, thereby overriding those abstract
members.
 A class that has at least one abstract method. Whether declared or inherited from an
abstract class, must be declared abstract.
U19CST62 - C# AND .NET PRGRAMMING 40
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

 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 ( );

U19CST62 - C# AND .NET PRGRAMMING 41


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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;

U19CST62 - C# AND .NET PRGRAMMING 42


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

}
}
Public static void main ( )
{
MyDerivedC mc = new MyDerivedC ( );
mc.MyMethod ( );
Console.WriteLine (―x= {0}‖, mc.Get x);
}
}

6. Explain Interface In Detail. (Nov 2013) (Apr 2013)(Nov 2018)


 An interface defines a contract by specifying a set of method prototypes specifying a set
of method prototypes to which each class that implements it must adhere.
 An interface in 100% abstract class.
 An interface provides a form for a class but now how to implement it.
 An interface defines what a class can do but now how the class will do it.
Rules on interface:
 An interface can inherit from multiple base interfaces. Interfaces can be implemented by
any class. An interface cannot implement any data type. An interface cannot be
instantiated. Interface can contain methods, properties, events and indexers. The interface
itself does not provide implementations for the members that it defines.
 The interface merely specifies that members must supply classes or struct to implement
the interface. A class or struct can implement several interfaces, thus enabling multiple
inheritances. A class that implements an interface partially must be declared abstract.
New, public, protected, internal and private are valid interface modifiers.
Implementing an Interface:
Implementing an Interface means providing implementations for its methods. Interfaces are
implemented using a ―;‖. Rules for implementing the interface methods are:
1. Must have the same signature and return type.
2. Cannot narrow the method accessibility Interface methods are implicitly public.
Example:
Public abstract class AccountInfo
{
Private double balance;
{
U19CST62 - C# AND .NET PRGRAMMING 43
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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 ();
}

U19CST62 - C# AND .NET PRGRAMMING 44


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Public class BankApp


{
Public static void main (String [] args)
{
Savings pesoAcct = new Savings ();
pesoAcct.Balance = 500;
pesoAcct.PrintAccountInfo ();
pesoAcct.Deposit (300);
pesoAcct.Withdraw (50);
pesoAcct.Console.WriteLine (―updated Balance:‖ +pesoAcct.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.

7. Explain Poymorphism In Detail. (Apr 2012) (Nov 2012)


 Polymorphism is the ability of different objects to respond to the same message in
different ways.
 This means that different objects can have very different method implementations for the
same message.
 Polymorphism is derived from 2 Latin words ―Poly‖ – ―many‖ & ―morph‖ – ―forms‖
 Polymorphism is the ability of objects belonging to different types to respond to methods
of the same name, each one according to the appropriate type – specific behavior.
Polymorphism can be classified into two types.
 Static Polymorphism
 Dynamic Polymorphism
U19CST62 - C# AND .NET PRGRAMMING 45
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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

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.ReadLine ();
}}}
METHOD OVERRIDING:
Dynamic Polymorphism is also called as Method Overriding.
Method Overriding allows a sub class to redefine methods of the same name from the super
class.
The key benefit or overriding is the ability to define/defer behavior specific to sub classes.
Which overridden method to call is based on object type and decided at runtime.
Method Overriding is also known as runtime polymorphism.
RULES OF METHOD OVERRIDING:
- An overridden method must have
 The same name
 The same number of parameters and types.
 The same return type as the overridden method.
- Overriding a method cannot narrow the method access level defined in the overridden
method.
- Methods declared as private, static, or sealed cannot be overridden.
- For a method to be overridable without any compilation error/warning, it should be
marked as virtual or abstract or override.
- A static method cannot override an instance method.
Example for Method Overriding:
Using System;
Class Square
{
Public double x;
Public Square (double x)
{
this.x = x;
}
U19CST62 - C# AND .NET PRGRAMMING 47
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Public Virtual double Area ()


{
return x*x;
}}
Class cube: Square
{
Public cube (double x): base (x)
{
}
Public override double Area ()
{
return (6*(base.Area());
}
}
Public Static void Main ()
{
double x =5.2;
Square S = new Square (x);
Square C = new cube (x);
Console.WriteLine (―Area of Square = ―, S.Area ());
Console.WriteLine (―Area of cube =‖, C.Area ());
}}

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.

8. Explain Arrays In Detail


U19CST62 - C# AND .NET PRGRAMMING 48
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

 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;
}}

Creating an Array Construction:


Constructing an array means creating an object of its declared type.
Example:
Public class Arraylist
{
Public static void Main (string [ ] args)
{
int [ ] numbers;
char [ ] letters, symbols;
string [ ] countries;
numbers = new int [3];
string [ ] currencies = new string [3];
}}

MANIPULATING ARRAYS:
Example:
Public class ArrayTest
{
Public static void Main (string [ ] args)

U19CST62 - C# AND .NET PRGRAMMING 50


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

{
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;

U19CST62 - C# AND .NET PRGRAMMING 51


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

numbers = new int [4,2,3];


can also be initialized as
int [,] numbers = new int [4,2]
{ {1,2}, {3,4}, {5,6}, {7,8}};
JAGGED ARRAY:
A Jagged array is an array whose elements are arrays. The elements of a jagged array can
be different dimensions and sizes.
Jagged arrays are also known as an array of arrays.
int [ ] [ ] x = new int [3] [ ];
x[0] = new int [3];
x[1] =new int [2];
x[2] =new int [4];

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
{

U19CST62 - C# AND .NET PRGRAMMING 54


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Public static void Main ()


{
Point mypoint = new Point ();
Point yourpoint = new Point (10,10);
Console.Write (―My Point‖);
Console.WriteLine (―x = {0}, y = {1}‖, mypoint x, mypoint y);
Console.Write (―Your Point‖);
Console.WriteLine (―x = {0}, y={1}‖, yourpoint x, yourpoint y);
}}
OUTPUT:
My Point: x=0; y=0
Your Point: x=10, y =10

10. Explain Operator Overloading In Detail. (Apr’16)


Operator Overloading, also known as overloading, provides a way to define and use
operators such as +, -, and / for user-defined classes or structs. It allows us to define/redefine the
way operators work with our classes and structs. The following table shows the operators and
their overloadability in C#.
OPERATORS OVERLOADABILITY
+, -, *, /, %, &, |, <<. All C# binary operators can
>> be overloaded.
+, -, !, ~, ++, --, true, All C# unary operators can
false be overloaded.
==, !=, <, >, <=, >= All relational operators can
be overloaded
&&, || They can‘t be overloaded
[ ] (Array index They can‘t be overloaded
operator)
( ) (Conversion They can‘t be overloaded
Operator)

U19CST62 - C# AND .NET PRGRAMMING 55


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

+=, -=, *=, /=, %= These compound


Assignment operators can
be overloaded. But in C#,
these operators are
automatically overloaded
when the respective binary
operator is overloaded.
=, ., ?:, ->, new, is, as, These operators can‘t be
sizeof overloaded in C#.

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 ()

U19CST62 - C# AND .NET PRGRAMMING 57


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

{
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‖);
}}

11. Explain Indexer In C# (May’14)


 C# introduces a new concept called Indexer. This is very useful for some situation. Let us
discuss something about Indexer.
U19CST62 - C# AND .NET PRGRAMMING 58
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

 Indexer concept is object act as an array.


 Indexer, an object to be indexed in the same way as an array.
 Indexer modifier can be private, public, protected or internal.
 The return type can be any valid C# types.
 Indexers in C# must have at least one parameter. Else the compiler will generate a
compilation error.
This [parameter]
{
Get
{
// get codes here
}
Set
{
// set codes goes here
}}

The general syntax is given below,


[modifiers] <type> this [<parameters>]
{
[get { <stmts>;}] // get Accessor
[set { <stmts>;}] // set Accessor
}
Where,
Modifiers – can be private, public, protected or internal.
Return type – can be any valid C# types.
this – is a special keyword in C# to indicate the object of the current class.
<parameters> - The formal argument – list specifies the parameters of the indexers.
Example for C# Indexer:
Using System;
Using System.Collections.Generic;
Using System.Text;
Namespace Indexers
{
Class ParentClass
U19CST62 - C# AND .NET PRGRAMMING 59
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

{
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 ();
}}}

12. Explain Collections In C#


C# collection is a class that provides more advanced mechanisms for gathering groups of
objects.
C# COLLECTIONS CLASSES:

U19CST62 - C# AND .NET PRGRAMMING 60


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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:

U19CST62 - C# AND .NET PRGRAMMING 61


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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

U19CST62 - C# AND .NET PRGRAMMING 62


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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,

U19CST62 - C# AND .NET PRGRAMMING 63


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Together these offer comparison, appending, inserting, conversion, copying, formatting,


indexing, joining, splitting, padding, trimming, removing, replacing and searching methods.
Consider this example, which uses Replace Insert and ToUpper.
Public class TestStringsApp
{
Public static void Main (String [ ] args)
{
String a =‖Strong‖;
String b = a.Replace (‗0‘, ‗I‘ );
Console.WriteLine (b);
String c = b.Insert (3, ―engthen‖);
String d = c.ToUpper ();
Console.WriteLine (d);
}}

The output from this application will be String STRENGTHENING.


String Formatting:
Both String.Format and WriteLine formatting are governed by the same formatting
Rules.
For example, the following three statements produce the same output.
Public class TestConsoleApp
{
Public static void Main (string [ ] args )
{
Console.WriteLine (123);
Console.WriteLine (―{0}‖, 123);
Console.WriteLine (―{0.D3}‖, 123);
}}

The output is as follows


123
123
123
We would get exactly the same results using String.Format directly.
String s = String.Format (―123‖);

U19CST62 - C# AND .NET PRGRAMMING 64


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

String t = String.Format (―{0}, 123);


String u = String.Format (―{0:D3}‖, 123);
Console.WriteLine (s);
Console.WriteLine (t);
Console.WriteLine (u);
Format Specifiers:
Standard Numeric Format strings are used to return strings in commonly used formats.
String and WriteLine Format Specifiers:
CHARACTER INTERPRETATION
C or c Currency
D or d Decimal
E or e Exponent
F or f Fixed Point
G or g General
N or n Number
R or r Round Trip
X or x Hex

Public class Formatspecapp


{
Public static void Main (string [ ] args)
{
int i =123456;
Console.WriteLine (―{0:C}‖,i); // £123,456.00
Console.WriteLine (―{0:D}‖.i); //123456
Console.WriteLine (―{0:E}‖.i); //1.234560E+005
Console.WriteLine (―{0:F}‖.i); // 123456.00
Console.WriteLine (―{0:G}‖.i); // 123456
Console.WriteLine (―{0:N}‖.i); // 123,456.00
Console.WriteLine (―{0:P}‖.i); // 12,345,600.00%
Console.WriteLine (―{0:X}‖.i); // 1E240
}}

Objects and ToString:

U19CST62 - C# AND .NET PRGRAMMING 65


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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

U19CST62 - C# AND .NET PRGRAMMING 66


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

{
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.

U19CST62 - C# AND .NET PRGRAMMING 67


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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.

14. Explain Regular Expressions In Detail.


The System.Text namespaces provides a number of classes for regular expression
processing. Regular Expressions offer a powerful, flexible and efficient strategy for processing
text.
Common Regular Expressions Meta characters:

U19CST62 - C# AND .NET PRGRAMMING 68


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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

U19CST62 - C# AND .NET PRGRAMMING 70


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

15.Explain Delegates And Events In Detail. (Nov’14)


DELEGATES:
A delegate allows the programmer to encapsulate a reference to a method inside a delegate
object.
 The delegate object can then be passed to code which can call the referenced method,
without having to know at compile time which method will be invoked.
 A delegate can reference a method only if the signature of the method exactly matches
the signature specified by the delegate type.
 Delegates are similar to function pointers in other languages like C++, however,
delegates are type-safe.
 There are 3 steps in defining and using delegates.
Declaration – A delegate declaration defines a class that is derived from the class
System.Delegate.
Instantiation – A delegate instance encapsulates an invocation list, which is a list of one or more
methods, each of which is referred to as a callable entity.
Invocation – Invoking a delegate instance with an appropriate set of arguments causes each of
the delegate instances callable entities to be invoked with the given set of arguments.
Note: Delegates run under the Caller‘s security permissions, not the declarer‘s permissions.
SINGLE CAST DELEGATE:
Using System;
Namespace TestconsoleApps
{
Public class SimpleDelegate
{
Public delegate int AddMulDelegate (int a, int b);
Public int AddNumber (int a, int b)
{
return (a + b);
}
Public int MulNumber (int a, int b)
{
return (a * b);
}
Static void Main ()
{
U19CST62 - C# AND .NET PRGRAMMING 71
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

SimpleDelegate simpdel = new SimpleDelegate ();


AddMulDelegateadddelegate = new AddMulDelegate (simpldel.AddNumber);
AddMulDelegatemuldelegate = new AddMulDelegate (simpdel.MulNumber);
IntaddAns = addDelegate (10,12);
IntmulAns = mulDelegate (10,10);
Console.WriteLine (―Result by Calling the AddNumber method using a Delegate:
{0}‖, addAns);
Console.WriteLine (―Result by calling the MulNumber method using a Delegate:
{0}‖, mulAns);
Console.ReadLine ();
}}}
MULTICAST DELEGATE:
Using System;
Using System.IO;
Namespace chap
{
Public class printtodevice
{
Static Fileatreamfstream;
Static StreamWriterSwriter;
Public delegate void PrintData (string s);
Public static void WriteConsole (string str);
{
Console.WriteLine (―{0} console‖, str);
}
Public static void WriteFile (string s)
{
Fstream = new FileStream (―C:\\storeData.txt‖, FileMode.Append,
FileAccess.Write);
Swriter = new StreamWriter (fstream);
S=S+‖file‖;
Swriter.WriteLine (s);
Swriter.Flush ():
Swriter.Close ();
Fstream.Close ();

U19CST62 - C# AND .NET PRGRAMMING 72


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

}
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 ()
{

U19CST62 - C# AND .NET PRGRAMMING 73


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Console.WriteLine (―Its Time to Wake up‖);


}
Example Program for both Delegates and Events:
Using System;
Using System.Collections.Generic;
Using System.Ling;
Using System.Text;
Using System.IO;
Namespace ConsoleApp3
{
Public class DelegateEvent
{
Public delegate void AttendanceLogHandler (string message);
Public event AttendanceLogHandlerEventLog;
Public void LogProcess ()
{
String reason = null;
Console.WriteLine (―Enter Your Name‖);
String username = Console.ReadLine ():
DateTime t = DateTime.Now;
Inthr = t.Hour;
Int m =t.Minute;
If (hr>=9)
{
Console.WriteLine (―Enter the reason‖);
Reason = Console.ReadLine ();
}
OnEventLog (―Logging the info of:‖ + username);
If (hr>=9)
OnEventLog (―Logged in at:‖ +hr.ToString () + ―:‖ + m.ToString () + ―not within
time because ―+ reason);
}
Protected void OnEventLog (string Message)
{
If (EventLog! =null)

U19CST62 - C# AND .NET PRGRAMMING 74


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

{
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 ();

U19CST62 - C# AND .NET PRGRAMMING 75


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

F1.Close ();
}}}

16. Explain Exception Handling In Detail. (Nov2013) (Nov 2012) (Apr’14)


 Exception Handling is an in built mechanism in .NET Framework to detect and handle
run time errors. The .Net Framework contains lots of standard exceptions. The exceptions
are anomalies that occur during the execution of a program. They can be because of user,
logic or system errors. If a user does not provide a mechanism to handle these anomalies,
the .NET run time environment provides a default mechanism, which terminates the
program execution.
 C# provides three keywords try, catch and finally to do exception handling. The try
encloses the statements that might throw an exception whereas catch handles an
exception if one exists. The general form try – catch finally in C# is shown below.

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.

U19CST62 - C# AND .NET PRGRAMMING 76


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

 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

Public static void Main ()


{
int x=0;
int div =0;
try
{
div =100/x;
Console.WriteLine (―Not Executed Line‖);
}
Catch (DivideByZeroException de)
{
Console.Writeline (―DivideByZeroException‖);
}
Catch (Exception ee)
{
Console.WriteLine (―Exception‖);
}
Finally
{
Console.WriteLine (―Finally Block‖);
}
Console.WriteLine (―Result is {0}‖, div);
}}
Standard Exceptions:
 There are two types of exceptions: exceptions generated by an executing program and
exceptions generated by the common language RunTime.System.Exception is the base
class for all exceptions in C#. Several exception classes inherit from this class including
ApplicationException and SystemException. These two classes from the basis for most
other runtime exceptions. Other exceptions that derive directly from System.Exception
include IOException, WebException etc.
 The common language Runtime throws SystemException. The ApplicationException is
thrown by a user program rather than the runtime. The SystemException includes the
ExecutionEngineException, StackOverflowException etc. It is not recommended that we
catch system Exceptions nor is it good programming practice to throw SystemExceptions
in our applications.
U19CST62 - C# AND .NET PRGRAMMING 78
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‖);
}}

U19CST62 - C# AND .NET PRGRAMMING 79


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

17. Discuss different ways in which C# is different from Java (Nov’15)


Features of C# Absent in Java
 C# includes more primitive types and the functionality to catch arithmetic exceptions.
 Includes a large number of notational conveniences over Java, many of which, such as
operator overloading and user-defined casts, are already familiar to the large community
of C++ programmers.
 Event handling is a "first class citizen"—it is part of the language itself.
 Allows the definition of "structs", which are similar to classes but may be allocated on
the stack (unlike instances of classes in C# and Java).
 C# implements properties as part of the language syntax.
 C# allows switch statements to operate on strings.
 C# allows anonymous methods providing closure functionality.
 C# allows iterator that employs co-routines via a functional-style yield keyword.
 C# has support for output parameters, aiding in the return of multiple values, a feature
shared by C++ and SQL.
 C# has the ability to alias namespaces.
 C# has "Explicit Member Implementation" which allows a class to specifically
implement methods of an interface, separate from its own class methods. This allows it
also to implement two different interfaces which happen to have a method of the same
name. The methods of an interface do not need to be public; they can be made to be
accessible only via that interface.
 C# provides integration with COM.
 Following the example of C and C++, C# allows call by reference for primitive and
reference types.
Features of Java Absent in C#
 Java's strictfp keyword guarantees that the result of floating point operations remain the
same across platforms.
 Java supports checked exceptions for better enforcement of error trapping and handling.
Philosophical Differences between the Languages
 There are no unsigned primitive numeric types in Java. While it is universally agreed that
mixing signed and unsigned variables in code is bad, Java's lack of support for unsigned
numeric types makes it somewhat unsuited for low-level programming.
 C# does not include checked exceptions. Some would argue that checked exceptions are
very helpful for good programming practice. Others, including Anders Hejlsberg, chief

U19CST62 - C# AND .NET PRGRAMMING 80


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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.

U19CST62 - C# AND .NET PRGRAMMING 81


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

 Methods in C# are non-virtual by default. In Java however, methods are virtual by


default. Virtual methods guarantee that the most overridden method of an object will be
called which is determined by the runtime. You always have to keep that in mind when
calling or writing any virtual method! If the method is declared as non-virtual, the
method to invoke will be determined by the compiler. This is a major difference of
philosophy between the designers of the Java and .NET platforms.
 Java 1.5's generics use type-erasure. Information about the generic types is lost when
Java source is compiled to bytecode. .NET 2.0's generics are preserved after compilation
due to generics support starting in version 2.0 of the .NET Common Language Runtime,
or CLR for short. Java's approach allows Java 1.5 binaries to be run in the 1.4 JRE, at the
cost of additional runtime typechecks.
 C# is defined by ECMA and ISO standards, whereas Java is proprietary, though largely
controlled through an open community process.
 The C# API is completely controlled by Microsoft, whereas the Java API is managed
through an open community process.
 The .NET run-time allows both managed and unmanaged code, enabling certain classes
of bugs that do not exist in Java's pure managed code environment but also allows
interfacing with existing code.

18. Write a C# program foroverloading binary operator (Nov’14)


Binary operator overloading:
using System;
namespacebinary_overload
{
classcomplexNumber
{
int x;
double y;
publiccomplexNumber(int real, double imagnary)
{
x = real;
y = imagnary;
}
publiccomplexNumber()
{

U19CST62 - C# AND .NET PRGRAMMING 82


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

}
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();
}
}
}

U19CST62 - C# AND .NET PRGRAMMING 83


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Note:-
The Method operator + () takes two argument (ComplexNumber) and add the two object in
same class.

19. What are the string handling methods? Describe. (Nov’13)


String methods:
1.clone() method
Clone() method creates and returns a copy of string object.
Syntax:
Objname.clone();
Ex:
stringstr = "Clone() Test";
stringclonedString = null;
clonedString = (String)str.Clone();
Console.WriteLine(clonedString);
2.compare() method:
Compare function compares two strings
intstring.Compare(string str1,string str2)
It returns an Integer indication lexical relationship between the two comprehends
Parameters:
string str1 : Parameter String
string str2 : Parameter String
Returns:
Integer : returns less than zero, zero or greater than zero.
Less than zero : str1 is less than str2
zero : str1 is equal to str2
Greater than zero : str1 is greater than str2
Example:
using System;
usingSystem.Collections;
U19CST62 - C# AND .NET PRGRAMMING 84
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

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";

U19CST62 - C# AND .NET PRGRAMMING 85


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Console.WriteLine(string.Concat(str1, str2));
Console.ReadKey();

4. The CSharpContains method


It returns true if and only if this string contains the specified sequence of char values.
boolstring.containe(string str)
Parameters:
String str - input String for search
Returns:
Boolean - Yes/No
If the str Contains in the String then it returns true
If the str does not Contains in the String it returns False
For ex: "This is a Test".Contains("is") return True
"This is a Test".Contains("yes") return False
Example:
stringstr = null;
str = "CSharp TOP 10 BOOKS";
if (str.Contains("TOP") == true)
{
Console.WriteLine("Exist ");
}
else
{
Console.WriteLine("Not Exist");
}
5. string Copy
CSharp String Copy method is create a new String object with the same content
stringstring.Copy(string str)
Parameters:
String str : The argument String for Copy method
Returns:
String : Returns a new String as the same content of argument String
Exceptions:
System.ArgumentNullException : If the argument is null.
EXAMPLE:

U19CST62 - C# AND .NET PRGRAMMING 86


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

string str1 = null;


string str2 = null;
str1 = "AHILA";
str2 = string.Copy(str1);
Console.WriteLine(str2);

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);

U19CST62 - C# AND .NET PRGRAMMING 88


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

PONDICHERRY UNIVERSITY QUESTIONS


2 MARKS
1. How C# relates to the .NET Framework? (Nov’13) (Ref.Qn.No.1, Pg.no.2)
2. What are important features of C#, which are adopted from other languages? (Apr’15) )
(Ref.Qn.No.11, Pg.no.4)
3. List out the member access modifiers in C# (APR 2012) ) (Ref.Qn.No.49, Pg.no.14)
4. What are limitations of operator overloading? (NOV 2013) ) (Ref.Qn.No.69, Pg.no.19)
5. What is a Delegate? (APRIL 2012) (Ref.Qn.No.72, Pg.no.19)
6. What is an event? (Apr’16) ) (Ref.Qn.No.75, Pg.no.20)
7. Use a diagram and briefly discuss the evolution of C# Language (Nov’15) (Ref.Qn.No.84,
Pg.no.21)
8. Distinguish clearly between value type and reference type in C# (Nov’15) (Apr’16) (Nov’13)
(Ref.Qn.No.85, Pg.no.22)
9. What is inclusion polymorphism? (Apr’16) (Ref.Qn.No.86, Pg.no.22)
10. List down the various types of Inheritance (Apr’15) (Ref.Qn.No.87, Pg.no.23)
11. How to declare a one-dimensional array in C# (Nov’14) (Ref.Qn.No.88, Pg.no.24)
12. what are the two forms of operator overloading in C#? (Nov’13) (Ref.Qn.No.89, Pg.no.24)
13. Define Object. (NOV’12) (Apr’16) (Ref.Qn.No.2, Pg.no.32)
14. Define Methods. (NOVEMBER 2012) (Ref.Qn.No.3, Pg.no.33)

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)

U19CST62 - C# AND .NET PRGRAMMING 89


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

10.Explain Operator Overloading In Detail. (Apr’16) (Ref.Qn.No.10, Pg.No.55)


11.What is meant by c# language fundamentals? (apr’15) (Ref.Qn.No.1, Pg.no.25)
12.Explain Delegates And Events In Detail. (Nov’14) (Ref.Qn.No.15, Pg.No.71)
13.Write a C# program for overloading binary operator (Nov’14) (Ref.Qn.No.18, Pg.no.82)
14.Explain Indexer In C# (May’14) (Ref.Qn.No.11, Pg.No.58)

U19CST62 - C# AND .NET PRGRAMMING 90

You might also like