C# Language Fundamentals Overview
C# Language Fundamentals Overview
Prepared by:
Dr. E. KODHAI, Prof/CSE
Mr. M. SHANMUGAM, AP/CSE
Dr. V. VIJAYAKUMAR, Assoc. Prof/CSE
UNIT II
.NET Languages: C# Language Fundamentals – Classes and Objects – Methods – Fields and
Properties - Inheritance and Polymorphism – Operator Overloading – Struts – Interfaces – Arrays
–Indexers and Collections – Strings and Regular Expressions – Handling Exceptions – Delegates
and Events.
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 [Link] 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
CS T54 - PLATFORM TECHNOLOGY 2
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
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.
CS T54 - PLATFORM TECHNOLOGY 3
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
[Link]
(
“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.
• The line separator character (U+2028)
CS T54 - PLATFORM TECHNOLOGY 5
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
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:
Arithmetic operators
CS T54 - PLATFORM TECHNOLOGY 8
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
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;
classPassByValue
CS T54 - PLATFORM TECHNOLOGY 9
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
{
staticint increment(intval)
{
return ++val;
}
public static void Main()
{
int a = 10;
[Link](“Value of a ‐ before calling increment is “ + a);
[Link](“Value returned by increment is “ + increment(a);
[Link](‘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;
[Link](“Value of a ‐ before calling increment is “ + a); increment( ref a);
[Link](‘Value of a - after calling increment is {0}”, a);
}
CS T54 - PLATFORM TECHNOLOGY 10
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
}
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);
[Link](“The sum of {0} and {1} is {2}”, x, y, sum);
}
}
40. Write a short note on parameter arrays (OR) params keyword (OR) variable argument
list
In C#, the methods can be defined to handle variable number of arguments using what
are known as parameter arrays. Parameter arrays are declared using the keyword params. This
can be combined with the formal parameter list and in such cases, it must be the last parameter. It
is permitted to use parameter arrays along with the value parameters, but it is not allowed to
combine the params modifier with the ref and out modifiers.
Ex:
using System;
classParamsTest
{
staticint sum(paramsint[] val)
{
int tot=0;
foreach (int i in val)
tot = tot + i;
return tot;
}
public static void Main()
{
[Link](“The sum of 40,50,60 is {0}”, sum(40,50,60));
[Link](“The sum of 2,3,12,15,17 is {0}”, sum(2,3,12,15,17));
[Link](“The sum of 12 is {0}”, sum(12));
}
}
Output:
The sum of 40,50,60 is 150
The sum of 2,3,12,15,17 is 49 The sum of 12 is 12
41. How the compiler selects a method for compilation?
The method selection involves following steps:
1. The compiler tries to find an exact match in which the types of actual parameters are
the same and uses that method.
2. If the exact match is not found, then the compiler tries to use the implicit conversions to the
actual arguments and then uses the method whose match is unique. If the conversion
creates multiple matches, then the compiler will generate an error message.
42. Can a method return more than one value in C#? Justify your answer.
Any method can return only one value if the return type is other than void. But in
C#, it is possible to return more than one value from the program using out parameter. For
example,
using System;
classReturnTest
{
staticint test(int a, out int b)
{
b = a + a;
return ++a;
}
public static void Main()
{
int x = 10, y;
[Link](“The value of x is {0}”, test(x,out y));
[Link](“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.
1. A derived class extends its direct base class. It can add new members to those it
[Link], 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.
52. What is the use of private constructors?
CS T54 - PLATFORM TECHNOLOGY 14
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
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;
}
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.
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.
Delegate is a method which is acting for another method. A delegate declaration defines a
class using the [Link] 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 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)
CS T54 - PLATFORM TECHNOLOGY 20
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
C# Versions
C# 1.0 – It was the first release and was included in Visual [Link].
C# 1.1 – It was released after the first release and Microsoft changed the Visual Studio to
Visual [Link] 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
CS T54 - PLATFORM TECHNOLOGY 21
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
class Maruthi
{
public virtual void Display()
{
[Link]("Maruthi Car");
}
}
class Esteem:Maruthi
{
public override void Display()
{
[Link]("Maruthi Esteem");
CS T54 - PLATFORM TECHNOLOGY 22
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
}
}
class Zen:Maruthi
{
public override void Display()
{
[Link]("Maruthi Zen");
}
}
class Inclusion
{
public static void Main()
{
Maruthi m=new Maruthi();
m=new Esteem();
[Link](); // prints Maruthi Esteem
m=new Zen();
[Link](); // 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
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
11 Marks
1. What is meant by c# language fundamentals? (Apr’15)
To analyze the C# language fundamentals we must analyze the following.
C# Source File Structure.
C# Keywords
Identifiers.
Variable and Data types.
Variable Declaration and Initialization
Operators
Flow Controls.
I. C# SOURCE FILE STRUCTURE
DECLARATION ORDER
1. Using Statement
It is used to reference the namespaces.
Example: Using System.
2. Namespace Declaration
It is used to logically group similar classes that have related functionality. In C# we
need to declare each class in a namespace. By default namespace is automatically
created with the same name as that of the project.
2. Multi-line Comment:
Example: /*
Created on Feb 22, 2005
First C# program
CS T54 - PLATFORM TECHNOLOGY 25
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
*/
3. Documentation Comment:
Example: ///<summary>
///</summary>
///<param> name=”args” </param>
WHITESPACES
Tabs and spaces are ignored by the compiler. They are used to improve the readability of the code.
CLASS
Every C# program includes at least one class definition. The class is the fundamental component
of all C# programs. Class is keyword.
Example: public class CSharpOne
{
……
……
……
}
A class definition contains all the variables and methods that make the program work. This is
contained in the class body indicated by the opening and closing braces.
BRACES
Braces are used for grouping statements or block of codes.
The left brace ({) indicates the beginning of a class body, which contains any variables and
methods the class needs.
The left brace also indicates the beginning of a method body.
For every left brace that opens a class or method we need a corresponding right brace (}) to close
the class or method.
A right brace always closes its nearest left brace.
MAIN () METHOD:
This line begins the Main() method. This is the line at which the program will begin executing.
Example: public static void Main(String[] args)
{
……
……
}
STRING ARGS []
III. IDENTIFIER:
An identifier is the name given by a programmer to a variable, statement label, method,
class, and interface.
- An identifier must begin with a letter.
- Subsequent characters must be letters, digits or underscore.
- An identifier must not be a C# keyword.
- Identifier must not be a C# keyword.
- Identifiers are case sensitive.
CS T54 - PLATFORM TECHNOLOGY 27
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
- 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
CS T54 - PLATFORM TECHNOLOGY 28
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
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
CS T54 - PLATFORM TECHNOLOGY 29
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
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
CS T54 - PLATFORM TECHNOLOGY 30
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
}
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;
[Link] (y);
If (y>10)
goto Out1;
x=x+1;
}
}
Out 1:
[Link] (“out of loop”);
8. Return statement:
The return branching statements is used to exit from the current method.
There are two forms:
- Return <value>;
- Return;
Example 1:
Public int sum (int x, int y) {
Return x+y;
}
Example 2:
CLASS:
CS T54 - PLATFORM TECHNOLOGY 32
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
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 ()
- 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 ()
{
[Link] (“TOOT TOOT!”);
}
Static void Main (string [] args)
{
Vehicle car = new vehicle ();
[Link] ();
}
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 ();
[Link] ();
}
FIELDS:
CS T54 - PLATFORM TECHNOLOGY 34
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
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.
{
……….
……….
}
Set
{
……….
……….
}
}
To complete the width method, we now need to add the code that processes the getting and
setting of the properties. This is relatively simple for the get accessor. When the property value is
requested, we will simply return the value from the class-level variable.
Public int width
{
Get
{
Return width;
}
Set
{
}
}
When using the set accessor, the value that the external objects is assigning to the property
is passed as a variable named “value”. This can be thought of as similar to a method parameter
even though its name is hidden. For the width property, we will validate the provided value before
storing it. If the value is negative or is greater than one hundred, an exception will be thrown and
the property will remain unchanged. This is possible because of the correct usage of the get and
set accessors.
Example:
Public int width
{
Get
{
Return width;
}
Set
{
If(value<0||value >100)
{
Throw new overflowException ();
}
Width value;
}}
Public int height
{
Get
{
Return height
}
USING PROPERTIES:
Properties of instantiated objects are accessed using the object name followed by the member
access operator (.) and the property name. The property can be read from and written to using
similar syntax as for a standard variable.
Example:
Static void main (String [] args)
{
Rectangle rect = new Rectangle ();
[Link] =50;
[Link] = 25;
Rectangle Square = new Rectangle ();
[Link] = [Link] = 40;
[Link] ([Link]); //Output:”25”
[Link] ([Link]); //Output:”40”
[Link] = 125;
}
READ ONLY PROPERTIES:
Example:
Public int Area
{
Get
{
return height*width;
}
}
Public int Perimeter
{
Get
{
return 2*(height + width);
}
}
4. Explain Inheritance in C#
Inheritance is the ability to derive new classes from existing ones. A derived class (“sub class”)
inherits the instance variables and method of the base class (“parent class”), and may add new
instance variables and methods. Inheritance defines a hierarchical relationship among classes
wherein one class shares the attributes and method defined in one or more classes.
Types of inheritance
Single Inheritance
Hierarchical Inheritance
Multilevel Inheritance
Multiple Inheritance
Hybrid Inheritance
Examples For various types of inheritance
Single Inheritance
Example: Animal
Dog
Hierarchical Inheritance
Example:
Animal
CS T54 - PLATFORM TECHNOLOGY 38
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
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).
All class inherits from the highest object class in the inheritance hierarchy.
CS T54 - PLATFORM TECHNOLOGY 39
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
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 [Link];
Using [Link];
Using [Link];
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);
{
[Link] (“Call to saving [Link] ( ) {0}”,
dwithdrawal);
}
}
Public class checking Account: BankAccount
{
Override public void withdrawal (double dwithdrawal)
{
[Link] (“call to checking [Link] ( ) {0}”,
dwithdrawal);
}
}
Class program
{
Static void main (string [ ] args)
{
SavingsAccountsa =new SavingsAccount ( );
[Link] (1000);
CheckingAccountca = new CheckingAccount ( );
[Link] (2000);
[Link] ( );
}
}
}
Snippet:
Using system;
// Abstract class
Abstract class MyBaseC
{
Protected int x= 100;
Protected int y= 150;
// Abstract method
Public abstract void
MyMethod ( );
// Abstract Property
Public abstract int Get x
{
Get;
}
}
Class MyDerivedc: MyBaseC
{
Public override void MyMethod ( )
{
X++;
}
// overriding property
Public override int Get x
{
Get
{
Return x+10;
}
}
Public static void main ( )
{
MyDerivedC mc = new MyDerivedC ( );
[Link] ( );
[Link] (“x= {0}”, [Link] x);
}
}
{
Get
{
Return balance;
}
Set
{
Balance = value;
}
}
Public abstract void PrintAccountInfo ();
}
Public class Savings: AccountInfo, BankOperations
{
Public void withdraw (double amount)
{
Balance = Balance-amount;
}
Public void Deposit (double amount)
{
Balance = Balance + amount;
}
Public double BalanceInquiry ()
{
Return Balance;
}
Public void PrintAccountInfo ()
{
[Link] (“Account Balance: “ +Balance);
}}
Public interface BankOperations
{
Public void Withdraw (double amount);
Public void Deposit (double amount);
Public double BalanceInquiry ();
}
Public class BankApp
{
Public static void main (String [] args)
{
Savings pesoAcct = new Savings ();
[Link] = 500;
[Link] ();
[Link] (300);
[Link] (50);
[Link] (“updated Balance:” +[Link] ());
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.
Dynamic Polymorphism
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
CS T54 - PLATFORM TECHNOLOGY 46
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
{
Static void Main ()
{
Class2 obj = new class2 ();
[Link] ([Link] (10, 20));
[Link] ([Link] (10, 15.70f));
[Link] ([Link] (10, 20, 30));
[Link] ();
}}}
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 TestClass
{
Public double x;
Public Square (double x);
{
this.x = x;
CS T54 - PLATFORM TECHNOLOGY 47
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
}
Public Virtual double Area ()
{
return x*x;
}}
Class cube: Square
{
Public cube (double x): base (x)
{
}
Public override double Area ()
{
return (6*([Link]());
}
}
Public Static void Main ()
{
double x =5.2;
Square S = new Square (x);
Square C = new cube (x);
[Link] (“Area of Square = “, [Link] ());
[Link] (“Area of cube =”, [Link] ());
}}
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.
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;
CS T54 - PLATFORM TECHNOLOGY 49
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
scores [2] = 9;
}}
Creating an Array Declaration:
Declaring an array means providing a name and it’s Data Type.
1. Single Declaration
2. Multiple Declaration
3. Array of Objects
Example:
Public class ArrayTest
{
Public static void Main (String [ ] args)
{
int [ ] numbers;
char [ ] letters, symbols;
string [ ] countries;
}}
MANIPULATING ARRAYS:
Example:
Public class ArrayTest
{
int [, , ] numbers;
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:
[Link] (“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)
{
[Link] (“Multi – Dimension Array Sample”);
String [,] string2DArray = new string [2,2] { {“Rosy”, “Amy”}, {“Peter”,
“Albert”}};
foreach (string str in String2DArray)
{
[Link] (str);
}
[Link] (“……”);
CS T54 - PLATFORM TECHNOLOGY 52
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
----------------------------------------------------------
{
Public static void Main ()
{
Point mypoint = new Point ();
Point yourpoint = new Point (10,10);
[Link] (“My Point”);
[Link] (“x = {0}, y = {1}”, mypoint x, mypoint y);
[Link] (“Your Point”);
[Link] (“x = {0}, y={1}”, yourpoint x, yourpoint y);
}}
OUTPUT:
My Point: x=0; y=0
Your Point: x=10, y =10
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 ()
{
[Link] (“{0}{1}”, x, y);
}
Public static complex operator + (complex c1, complex c2)
CS T54 - PLATFORM TECHNOLOGY 56
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
{
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);
[Link] (); //displays 10 &20
Complex c2 = new Complex (20,30);
[Link] (); //displays 20 & 30
Complex c3 = new Complex ();
c3 =c1 + c2;
[Link] (); // 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 ()
{
[Link] (“{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 ()
{
[Link] (). GetHashCode ();
}
Class Myclient
{
Public static void Main ()
{
Complex c1 = new Complex (10,20);
[Link] (); //displays 10 & 20
Complex c2 = new Complex (10, 20);
[Link] (); //displays 10 & 20
Complex c3 = c2;
[Link] (); //displays 10 & 20
if ([Link] (c2))
[Link] (“OK”);
Else
[Link] (“NOT OK”);
If ([Link] (c3))
[Link] (“OK1”);
}}
{
Private string [ ] range = new string [5];
Public string this [ intindexrange]
{
Get
{
Return range [ indexrange];
}
Set
{
Range [indexrange] = value;
}}}
Class ChildClass
{
Public static void Main ()
{
ParentClassobj = new ParentClass ();
obj [0] =”ONE”;
obj [1] =”TWO”;
obj [2] =”THREE”;
obj [3] =”FOUR”;
obj [4] =”FIVE”;
[Link] (“Welcome to C# Home Page/n”);
[Link] (“\n”);
[Link] (“{0}\n, {1}\n, {2}\n, {3}\n, {4}\n”, obj [0], obj [1],
obj [2], obj [3], obj [4]);
[Link] ();
[Link] ();
}}}
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 [Link] namespaces while
the ArrayList class is contained within the [Link] 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 [Link];
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> ();
[Link] (“Red”);
[Link](“Green”);
[Link](“Yellow”);
[Link](“Purple”);
[Link](“Orange”);
Accessing List Items:
Individual items in a list may be accessed using the index value of the item (keeping in mind that
the first item is index 0, the second index 1 and so on). The index value is placed in square
brackets after the list name. For example, to access the second item in the colorlist object.
[Link] (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)
{
[Link] (color);
}
When compiled and executed, the above code will output each of the color strings in the color
strings in the colorlist objects:
[Link] (“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.
[Link] (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.
[Link] ();
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 [Link]
() method returns the index value of a matching item in a List. For example, the following code
sample will output the value 2, which is the index position of the “Yellow” string.
[Link] (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
All the basic types have tostring method, which is inherited from the object type, and all
the numeric types have a parse method, which takes the string representation of a number and
returns you its equivalent numeric value.
Public class NumParsingApp
{
Public static void Main (string [ ] args)
{
int i = [Link] (“12345”);
[Link] (“i={0}”,i);
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 [Link] (S))
{
[Link] (ss);
}}}
OUTPUT:
Once
Upon
A Time
In
America
Match and Match Collection:
The [Link] 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)
{
Regex r = new Regex (“in”);
Match m = [Link] (“Matching”);
If ([Link])
{
CS T54 - PLATFORM TECHNOLOGY 69
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
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 [Link].
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 intAddMulDelegate (int a, int b);
Public intAddNumber (int a, int b)
{
return (a + b);
}
Public intMulNumber (int a, int b)
{
return (a * b);
}
Static void Main ()
{
SimpleDelegatesimpdel = new SimpleDelegate ();
AddMulDelegateadddelegate = new AddMulDelegate ([Link]);
AddMulDelegatemuldelegate = new AddMulDelegate ([Link]);
IntaddAns = addDelegate (10,12);
IntmulAns = mulDelegate (10,10);
CS T54 - PLATFORM TECHNOLOGY 71
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
INSTANTIATION
RingAlarmobj = new TimeToRise (wakeup);
INVOCATION
RingAlarm ();
TimeToRise ();
Public void Wakeup ()
{
[Link] (“Its Time to Wake up”);
}
Example Program for both Delegates and Events:
Using System;
Using [Link];
Using [Link];
Using [Link];
Using [Link];
Namespace ConsoleApp3
{
Public class DelegateEvent
{
Public delegate void AttendanceLogHandler (string message);
Public event AttendanceLogHandlerEventLog;
Public void LogProcess ()
{
String reason = null;
[Link] (“Enter Your Name”);
String username = [Link] ():
DateTime t = [Link];
Inthr = [Link];
Int m =[Link];
If (hr>=9)
{
[Link] (“Enter the reason”);
Reason = [Link] ();
}
OnEventLog (“Logging the info of:” + username);
If (hr>=9)
OnEventLog (“Logged in at:” +[Link] () + “:” + [Link] () + “not within
time because “+ reason);
}
Protected void OnEventLog (string Message)
{
If (EventLog! =null)
{
EventLog (Message);
}}}
Public class Attendance Logger
{
FileStreamFs;
StreamWriterSw;
Public Attendance Logger (string fn)
{
Fs = new FileStream (Fn, [Link], [Link]);
Sw = new StreamWriter (Fs);
}
Public void Logger (string LogInfo)
{
[Link] (LogInfo);
}
Public void close ()
{
[Link] ();
[Link] ();
}}
Public class RecordAttendance
{
Static void Logger (string LogInfo)
{
[Link] (LogInfo);
}
Static void Main (string [ ]args)
{
Attendance Logger F1 = new Delegate AttendanceLogger (“E:\\[Link]”);
DelegateEvent De = new DelegateEvent ();
[Link] + = new [Link] (logger);
[Link] += new [Link] ([Link]);
[Link] ();
[Link] ();
[Link] ();
}}}
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.
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.
CS T54 - PLATFORM TECHNOLOGY 76
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
{
div =100/x;
[Link] (“Not Executed Line”);
}
Catch (DivideByZeroException de)
{
[Link] (“DivideByZeroException”);
}
Catch (Exception ee)
{
[Link] (“Exception”);
}
Finally
{
[Link] (“Finally Block”);
}
[Link] (“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 [Link] 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 [Link]
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.
- [Link]
- [Link]
- [Link]
- [Link]
- [Link]
CS T54 - PLATFORM TECHNOLOGY 78
Downloaded by Boovaneswari Balachandar (boovana2825@[Link])
lOMoARcPSD|53141004
- [Link]
- [Link]
- [Link]
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)
{
[Link] (“User Defined Exception”);
}}
Class Myclient
{
Public static void Main ()
{
Try
{
Throw new MyException (“ROSE”);
}
Catch (Exception e)
{
[Link] (“Exception caught here” + [Link] ());
}
[Link] (“Last Statement”);
}}
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 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.
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.
{
complexNumber c = new complexNumber();
c.x=c1.x+c2.x;
c.y=c1.x-c2.y;
return c;
}
public void show()
{
[Link](x);
[Link]("+j"+y);
[Link]();
}
}
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;
[Link]("p=");
[Link]();
[Link]("q=");
[Link]();
[Link]("r=");
[Link]();
[Link]();
}
}
}
Note:-
The Method operator + () takes two argument (ComplexNumber) and add the two object in
same class.
str1 = "csharp";
str2 = "CSharp";
int result = 0;
result = [Link](str1, str2);
[Link](result);
str1 = "CSharp";
result = [Link](str1, str2);
[Link](result);
[Link]();
}
}
}
[Link]
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";
[Link]([Link](str1, str2));
[Link]();
It returns true if and only if this string contains the specified sequence of char values.
[Link](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 ([Link]("TOP") == true)
{
[Link]("Exist ");
}
else
{
[Link]("Not Exist");
}
5. string Copy
CSharp String Copy method is create a new String object with the same content
[Link](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:
[Link] : If the argument is null.
EXAMPLE:
string str1 = null;
string str2 = null;
str1 = "AHILA";
str2 = [Link](str1);
[Link](str2);
6. String Equals
This function is to check the specified two String Object values are same or not
[Link](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()"
[Link](Str1,Str2) returns True
[Link]([Link],Str2) returns False
Because the String Objects values are different
Example:
string str1 = "ANI";
string str2 = "ani";
if ([Link](str1, str2))
{
[Link]("Equal ");
}
else
{
[Link]("not Equal ");
}
7. string Length
The Length property in String Class returned the number of characters occurred in a String.
[Link]
Returns:
Integer : The number of characters in the specified String
example:
"This is a Test".Length returns 14.
Example:
stringstr = null;
str = "ahila";
[Link]([Link]);
11 Marks
1.a) What are the string handling methods? Describe. (NOVEMBER 2013) ([Link].19,
[Link].84)
b) Write a short note on interface properties and interface indexers. ([Link].6, [Link].43)
[Link] in detail about fundamental of exception handling in C#. (NOVEMBER 2013)
([Link].16, [Link].76)
[Link] notes on the following: (APRIL 2012)
a. Access Modifiers ([Link].49, [Link].13)
b. Structs ([Link].9, [Link].54)
c. Static classes.
4. Explain Poymorphism In Detail. (Apr 2012) (Nov 2012) ([Link].7, [Link].45)
[Link] about Polymorphism? Give an examples. (NOVEMBER 2012) ([Link].7, [Link].45)
[Link] in detail Exception Handling. . (NOV2013) (NOV 2012) (Apr’14) ([Link].16,
[Link].76)
[Link] in detail about interfaces in .NET. (APRIL 2013) ([Link].6, [Link].43)
[Link] in detail about properties in .NET. (APRIL 2013) ([Link].3, [Link].33)
[Link] different ways in which C# is different from Java (Nov’15) ([Link].17, [Link].80)
Operator overloading in C# is primarily used in mathematical modeling, graphical, and financial programs where it simplifies operations on classes representing objects like coordinates or money . Despite its utility, it faces limitations such as implicit overloading of compound assignments and mutual dependency in relational operators like == and !=. Furthermore, new operators cannot be introduced, and changes to syntax rules like operands, precedence, and associativity are not permitted .
C# enhances coding efficiency and ease of use by integrating features from other languages, like Java's class grouping and reference handling methods, making code more manageable and organized. From Visual Basic, C# adopts intuitive form design approaches such as drag-and-drop control placement and event handler scripting, which simplify the UI programming process. This combination allows developers to harness the strengths of multiple languages within a single coding environment .
The immutable nature of the .NET string class means that once a string is created, its value cannot be changed. This leads to a scenario where any modification to a string results in the creation of a new string object. While this ensures that strings are thread-safe and reduces unintended side-effects from modifications, it can also lead to increased memory usage when numerous modifications are performed. To mitigate this, the StringBuilder class is often used as it allows for efficient and mutable string manipulation without the overhead associated with creating new string instances .
C# modernizes C++ by introducing features such as automatic garbage collection, versioning support, and strict type-safety. It also incorporates properties for accessing data members, delegates and events, boxing and unboxing, as well as web services. These advancements simplify memory management and enhance security, making C# more suitable for modern web technology and application development than C++ .
C++ suffers from issues such as long cycle-time, lack of true object-orientation, poor type-safety, and limited support for web technologies. It is also prone to costly programming errors, memory leakages, and lacks versioning support . C# addresses these limitations by incorporating automatic garbage collection, ensuring strict type-safety, and providing built-in support for web services, thus making it more robust and efficient for developing web-based applications .
String interning is a memory management optimization where identical string literals are stored only once, a practice that reduces the overall memory footprint of an application. This is particularly beneficial in C# since it minimizes duplicate data storage and accelerates the process of comparing strings by allowing reference equality checks instead of content comparisons. Interning is automatically handled by the runtime, thus simplifying application development and ensuring consistent performance improvements without requiring explicit developer intervention .
C# implements polymorphism through two primary mechanisms: operation polymorphism and inclusion polymorphism. Operation polymorphism is achieved using method and operator overloading, a process known as early or static binding, enabling the compiler to select appropriate methods based on argument matching at compile time . Inclusion polymorphism is facilitated using virtual methods, allowing runtime method selection, thus enabling objects to behave differently in different contexts .
C# facilitates modern application development by being intrinsically object-oriented and web-enabled, which are areas where Visual Basic lacks, especially as Visual Basic is not a true object-oriented language, making it difficult to scale large applications . C# also retains powerful features discarded by Java, like operator overloading, and offers better interoperability with other languages, supported by the .NET Framework . Additionally, C# combines the productivity of Visual Basic, the power of C++, and the elegance of Java, thus catering to high-level application demands .
Delegates in C# play a critical role in event handling by acting as a reference point for methods, essentially functioning as type-safe pointers. They allow methods to be treated as first-class objects, meaning that methods can be passed and executed indirectly. In event handling, a delegate defines the signature that event methods must match, ensuring consistency and eliminating runtime errors . This model enhances flexibility and promotes decoupled architectures by allowing dynamic method invocation and event-driven interaction .
C# is uniquely suited for component-oriented programming within the .NET framework as it is the only language explicitly designed for .NET. It simplifies and modernizes C++ by integrating language features like versioning support and strict type-safety, which are crucial for maintaining component integrity over time. Additionally, C# supports properties to manage data member access and uses delegates to provide event-driven programming, enhancing modularity and reducing complexity in component design .