Programming for Application Development Notes
Programming for Application Development Notes
DIGITAL NOTES
ON
Course Objectives:
1. To get an overview of the various technologies, which can help in the implementation of
the various liveProject.
2. To Understand the Basic Concepts ofC#
3. To Understand the Exception HandlingMechanisms
4. To Understand the Various Concepts of .netAssemblies
UNIT II: Developing Console Application: Introduction to Project and Solution in Studio-
Entry point method - Main. - Compiling and Building Projects -Using Command Line
Arguments - Importance of Exit code of an application- Different valid forms of Main-
Compiling a C# program using command line utility [Link]-Data types - Global, Stack
and Heap Memory- Common Type System-Reference Type and Value Type- Data types &
Variables Declaration- Implicit and Explicit Casting
UNIT IV: Delegates And Events: Understanding the .NET Delegate type, defining a
Delegate Type in C#, The System. Multicast Delegate and System. Delegate Base Classes,
PROGRAMMING WITH .NET ASSEMBLIES: Configuring .NET Assemblies, defining
Custom Namespaces, The role of .NET Assemblies, Understanding the Format of a .NET
assembly, Building and Consuming a Single-File Assembly, Building and Consuming a
Multifile Assembly, Understanding Private Assembly, Understanding Shared Assembly,
Consuming a Shared Assembly, Configuring Shared assemblies.
TEXT BOOKS:
[Link] Troelsen (2010), Pro C# and the .NET 4 Platform, 5th edition, Springer (India)
Private Limited, New Delhi,India.
REFERENCE BOOKS:
1.E. Balagurusamy (2004), Programming in C#, 5th edition, Tata McGraw-Hill, New Delhi,
India.
[Link] Schildt (2004), The Complete Reference: C#, Tata McGraw-Hill, New Delhi,
India.
[Link] Robinson, Christian N agel, Karli Watson, Jay Gl (2006), Professional C#, 3rd
edition, Wiley &Sons,India.
Course Outcome:
Upon completion of the subject, students will be able to:
1. Implementation of Oops Concepts [Link]
2. Be able to Implement, Compile, Test & Run ApplicationsPrograms.
3. Demonstrate the ability to use Exception HandlingMechanisms.
4. Able to Develop Applications [Link],C#.
UNIT I
[Link] Framework Introduction
The .NET framework is a pure object oriented, that similar to the Java language. But it is not
a platform independent as the Java. So, its application runs only to the windows platform.
The main objective of this framework is to develop an application that can run on
the windows platform. The current version of the .Net framework is 4.8.
Framework Components:
Net Framework is a platform that provides tools and technologies to develop Windows, Web
and Enterprise applications.
.Net Framework provides runtime environment called Common Language Runtime (CLR).It
provides an environment to run all the .Net Programs. The code which runs under the CLR is
called as Managed Code. Programmers need not to worry on managing the memory if the
programs are running under the CLR as it provides memory management and thread
management.
Programmatically, when our program needs memory, CLR allocates the memory for scope
and de-allocates the memory if the scope is completed.
Language Compilers (e.g. C#, [Link], J#) will convert the Code/Program to Microsoft
Intermediate Language (MSIL) intern this will be converted to Native Code by CLR.
There are currently over 15 language compilers being built by Microsoft and other companies
also producing the code that will execute under CLR.
This is also called as Base Class Library and it is common for all types of applications i.e. the
way you access the Library Classes and Methods in [Link] will be the same in C#, and it is
common for all other languages in .NET.
The following are different types of applications that can make use of .net class library.
1. Windows Application.
2. Console Application
3. Web Application.
4. XML Web Services.
5. Windows Services.
In short, developers just need to import the BCL in their language code and use its predefined
methods and properties to implement common and complex functions like reading and
writing to file, graphic rendering, database interaction, and XML document manipulation.
Below are the few more concepts that we need to know and understand as part of this .Net
framework.
It describes set of data types that can be used in different .Net languages in common. (i.e),
CTS ensures that objects written in different .Net languages can interact with each other.
For Communicating between programs written in any .NET complaint language, the types
have to be compatible on the basic level.
Value types:
Value types directly contain their data, and instances of value types are either allocated on the
stack or allocated inline in a structure. Value types can be built-in (implemented by the
runtime), user-defined, or enumerations.
Reference types:
Reference types store a reference to the value's memory address, and are allocated on the
heap. Reference types can be self-describing types, pointer types, or interface types. The type
of a reference type can be determined from values of self-describing types. Self-describing
types are further split into arrays and class types. The class types are user-defined classes,
boxed value types, and delegates.
It is a sub set of CTS and it specifies a set of rules that needs to be adhered or satisfied by all
language compilers targeting CLR. It helps in cross language inheritance and cross language
debugging.
It describes the minimal and complete set of features to produce code that can be hosted by
CLR. It ensures that products of compilers will work properly in .NET environment.
Sample Rules:
1. Representation of text strings
2. Internal representation of enumerations
3. Definition of static members and this is a subset of the CTS which all .NET languages
are expected to support.
4. Microsoft has defined CLS which are nothing but guidelines that language to follow so
that it can communicate with other .NET languages in a seamless manner.
Framework Versions:
Types of Applications:
Window client applications: Applications that run on windows O.S Windows forms and
WPF(Windows presentation formation) are two major technologies to develop Windows
applications.
Components and Controls: Libraries used to build something that is easily sharable and
distributable.
Web Applications:
Ex:[Link],[Link]
Mobile Apps:
C# supports native mobile App development Via Xamarin,it is a part of Visual studio 2017
or later versions.
[Link] Namespaces:
[Link]("Hello World!");
System is a namespace and Console is a class in that namespace. The using keyword can be
used so that the complete name is not required, as in the following example:
using System;
[Link]("Hello");
[Link]("World!");
2. Declaring your own namespaces can help you control the scope of class and method names
in larger programming projects. Use the namespace keyword to declare a namespace, as in
the following example:
using System;
namespace First {
public class Hello
{
public void sayHello()
{
[Link]("Hello First Namespace"); }
} }
namespace Second
{
public class Hello
{
public void sayHello()
{
[Link]("Hello Second Namespace"); }
}
}
using System;
using First;
using Second;
namespace First {
public class Hello
{
public void sayHello() { [Link]("Hello Namespace"); }
}
}
namespace Second
{
public class Welcome
{
public void sayWelcome()
{
[Link]("Welcome Namespace");
}
}
}
MSIL
Metadata
Metadata describes the characteristics of every “type” living within the binary.
For example, if you have a class named Sports Car, the type metadata describes details such
as Sports Car’s base class, which interfaces are implemented by Sports Car (if any), as well
as a full description of each member supported by the Sports Car type.
In addition to CIL and type metadata, assemblies themselves are also described using
metadata, which is officially termed a manifest. The manifest contains information about the
current version of the assembly.
PE Files
The Portable Executable (PE) format is a file format for executables, object code, and DLLs,
used in 32-bit and 64-bit versions of Windows operating systems. The PE file format was
defined to provide the best way for the Windows Operating System to execute code and also
to store the essential data which is needed to run a program.
CLR is the heart of .NET framework. Common Language Runtime (CLR) manages the
execution of programs written in any language that uses the .NET Framework, for
example C#, [Link], F# and so on. Programmers write code in any language,
including [Link], C# and F# when they compile their programs into an intermediate form of
code called CIL in a portable execution file (PE) that can be managed and used by the CLR
and then the CLR converts it into machine code to be executed by the processor.
Types of codes:
• Managed Code
• Unmanaged Code
Managed Code
The code, which is developed in .NET framework, is known as Managed code. This code is
directly executed by CLR with help of managed code execution. Managed code uses CLR
which in turns looks after your applications by managing memory, handling security,
allowing cross - language debugging, and so on.
Unmanaged Code
The code, which is developed outside .NET Framework is known as unmanaged code.
Unmanaged code is executed with help of wrapper classes.
void MakeACar()
{
// If myCar is the only reference to the Car object,
// it *may* be destroyed when this method returns.
Car myCar = new Car();
}
once this method call completes, the myCar reference is no longer reachable, and the
associated Car object is now a candidate for garbage collection. When the C# compiler
encounters the new keyword, it emits a CIL newobj instruction into the method
implementation.
The newobj instruction tells the CLR to perform the following core operations:
• Calculate the total amount of memory required for the object to be allocated (including the
memory required by the data members and the base classes).
• Examine the managed heap to ensure that there is indeed enough room to host the object to
be allocated. If there is, the specified constructor is called and the caller is ultimately returned
a reference to the new object in memory.
• Finally, before returning the reference to the caller, advance the next object pointer to point
to the next available slot on the managed heap.
Application Roots :
The Common Language Runtime (CLR) allocates large objects on the Large Object Heap
(LOH).garbage collector never compacts this heap. There may not be enough room for a new
object even with enough available memory. This causes the CLR to throw an inappropriately
named OutOfMemoryException.
The garbage collector uses three segments, called generations, for small objects:
• Generation 0
• Generation 1
• Generation 2
The CLR allocates memory for new objects in Generation 0. When this heap is full, the
garbage collector discards objects no longer in use and promotes surviving objects (referred
to as live objects) to Generation 1.
The Generation 0 heap is then available to hold more newly created objects. When
insufficient, the garbage collector repeats this process for Generation 1, and if still
insufficient, continues with Generation 2.
The bottom line is newer objects (such as local variables) will be removed quickly, while
older objects (such as a program’s application object) are not “bothered” as often.
At the time of compilation, all language-specific data types are converted into CLR’s data
type.
This data type system of CLR which is common to all programming languages of .NET is
known as CTS.
Understanding CTS
In the world of .NET, type is simply a general term used to refer to a member from the set
{class, interface, structure, enumeration, delegate}.
Interfaces are nothing more than a named collection of abstract member definitions, which
may be supported (i.e., implemented) by a given class or structure. In C#, interface types are
defined using the interface keyword. By convention, all .NET interfaces begin with a capital
letter I
// A C# structure type.
struct Point {
// Structures can contain fields.
public int xPos, yPos;
// Structures can contain parameterized constructors.
public Point(int x, int y)
{ xPos = x; yPos = y;}
// Structures may define methods.
public void PrintPosition()
{ [Link]("({0}, {1})", xPos, yPos);
}
}
Enumerations are a handy programming construct that allow you to group name/value pairs.
// A C# enumeration type.
enum CharacterType
{
Wizard = 100, Fighter = 200, Thief = 300
}
CLS stands for Common Language Specification and it is a subset of CTS. It defines a set of
rules and restrictions that every language must follow which runs under the .NET framework.
The languages which follow these set of rules are said to be CLS Compliant. For example, a
method with parameter of "unsigned int" type in an object written in C# is not CLS-
compliant, just as some languages, like [Link], do not support that type it would be ideal to
have a baseline to which all .NET-aware languages are expected to conform(follow certain
rules).
The CLS is ultimately a set of rules that compiler builders must conform to if they intend
their products to function seamlessly within the .NET universe.
Rule 1: CLS rules apply only to those parts of a type that are exposed outside the defining
assembly.
The implementation logic for a member may use any number of non-CLS techniques, as the
outside world won’t know the difference.
class Calc
{ // Exposed unsigned data is not CLS compliant!
public ulong Add(ulong x, ulong y)
{ return x + y; }
}
However, if you were to only make use of unsigned data internally in a method as follows,,
class Calc
{
public int Add(int x, int y)
{ // As this ulong variable is only used internally
// we are still CLS compliant.
ulong temp = 0; ... return x + y;
}}
Pre-JIT Compiler
Pre-JIT Compiler: All the source code is compiled into the machine code at the same time in
a single compilation cycle using the Pre-JIT Compiler.
Normal JIT Compiler: The source code methods that are required at run-time are compiled
into machine code the first time they are called by the Normal JIT Compiler. After that, they
are stored in the cache and used whenever they are called again.
Econo JIT Compiler: The source code methods that are required at run-time are compiled into
machine code by the Econo JIT Compiler. After these methods are not required anymore,
they are removed.
UNIT II
Developing Console Application
Command Line arguments:
The arguments which are passed by the user or programmer to the Main() method is termed
as Command-Line Arguments.
Main() method is the entry point of execution of a program. Main() method accepts array of
strings. But it never accepts parameters from any other method in the program.
In C# the command line arguments are passed to the Main() methods by stating as follows:
static void Main(string[] args)
or
EX:
using System;
namespacefirstsolution
{
classCmdarg1
{
staticvoidMain(String[] args)
{
[Link](args[0]);
}
}
}
The above program can be executed in the command prompt
To specify the command line arguments in Visual Studio , double-click the Properties icon
from Solution Explorer and select the Debug tab on the left side. From there, specify values
using the command-line arguments text box.
C# | foreach Loop
foreach loop is used to iterate over the elements of the collection. The collection may be an
array or a list. It executes for each element present in the array.
It is necessary to enclose the statements of foreach loop in curly braces {}.
Instead of declaring and initializing a loop counter variable, you declare a variable that
is the same type as the base type of the array, followed by a colon, which is then
followed by the array name.
In the loop body, you can use the loop variable you created rather than using an indexed
array element.
Syntax:
foreach(data_typevar_name in collection_variable)
// statements to be executed
Finally, you are also able to access command-line arguments using the static
GetCommandLineArgs() method of the System. Environment type. The return value of this
method is an array of strings. The first index identifies the name of the application itself,
while the remaining elements in the array contain the individual command-line arguments.
Note that when using this approach, it is no longer necessary to define Main() as taking a
string array as the input parameter, although there is no harm in doing so.
using System;
namespace firstsolution
{
class cmdarg
{
static void Main()
{
string[] theArgs = [Link]();
foreach (string arg in theArgs)
[Link]("Arg: {0}", arg);
}
}
}
string types as the single input parameter. This is not the only possible form of Main(), however. It is
permissible to construct your application’s entry point using any of the following signatures
(assuming it
return 0;
return 0;
C# Data Types:
A data type specifies the size and type of variable values. It is important to use the correct
data type for the corresponding variable; to avoid errors, to save time and memory, but it will
also make your code more maintainable and readable. The most common data types are:
Note that many numerical data types derive from a class named [Link].
Descendents of Value Type are automatically allocated on the stack and therefore have a very
predictable lifetime and are quite efficient. On the other hand, types that do not have
[Link] in their inheritance chain (such as [Link], [Link],
[Link], [Link], and [Link]) are not allocated on the stack, but on
the garbage-collected heap.
C# keyword (such as int) is simply shorthand notation for the corresponding system type (in
this case, System.Int32), the following is perfectly legal syntax, given that System.Int32 (the
C# int) eventually derives from [Link] and therefore can invoke any of its public
members, as illustrated by this additional helper function:
static void ObjectFunctionality()
{
[Link]("=>[Link] Functionality:");
Members of [Link]
C# textual data is represented by the string and char keywords, which are simple shorthand
notations for [Link] and [Link], both of which are Unicode under the hood. As
you may already know, a string represents a contiguous set of characters (e.g., "Hello"),
while the char can represent a single slot in a string (e.g., 'H').
The [Link] type provides you with a great deal of functionality beyond the ability to
hold a single point of character data. Using the static methods of [Link], you are able to
determine whether a given character is numerical, alphabetical, a point of punctuation, or
whatnot. Consider the following method:
String Concatenation
string variables can be connected together to build larger strings via the C# + operator. As
you mayknow, this technique is formally termed string concatenation. Consider the following
new helper
function:
C# Type Casting
type casting is when you assign a value of one data type to another type.
In C#, there are two types of casting:
Implicit Casting (automatically) - converting a smaller type to a larger type size
char -> int -> long -> float -> double
Explicit Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char
Implicit Casting
Implicit casting is done automatically when passing a smaller size type to a larger size type:
Example
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
[Link](myInt); // Outputs 9
[Link](myDouble); // Outputs 9
Explicit Casting
Explicit casting must be done manually by placing the type in parentheses in front of the
value:
This type of conversion is required when working with the user input.
Example
// Type your username and press enter
[Link]("Enter username:");
// Create a string variable and get user input from the keyboard and store it in the variable
string userName = [Link]();
// Print the value of the variable (userName), which will display the input value
[Link]("Username is: " + userName)
The [Link]() method returns a string. Therefore, you cannot get information from
another data type, such as int. The following program will cause an error:
Example
[Link]("Enter your age:");
int age = [Link]();
[Link]("Your age is: "+ age);
C# structures:
The C# structures have the following features −
Structures can have methods, fields, indexers, properties, operator methods, and
events.
Structures can have defined constructors, but not destructors. However, you cannot
define a default constructor for a structure. The default constructor is automatically
defined and cannot be changed.
Unlike classes, structures cannot inherit other structures or classes.
Structures cannot be used as a base for other structures or classes.
A structure can implement one or more interfaces.
struct Coordinate
{
public int x;
public int y;
namespacefirstsolution
{
structsample1
{
publicint a, b;
publicsample1(intx,int y)
{
a = x;b = y;
}
publicvoiddisplay()
{
[Link]("a={0},b={1}", a, b);
}
}
classstruct2cs
{
staticvoidMain()
{
sample1 s1 = new sample1(3, 4);
sample1 s2;
s2 = s1;
[Link]("before change,S1 object");
[Link]();
[Link]("before change, S2 object");
[Link]();
s2.b = 10;
[Link]("After change, S1 object");
[Link]();
[Link]("After change ,S2 object");
[Link]();
}
}
}
namespacefirstsolution
{
classsample2
{
publicint a, b;
publicsample2(int x, int y)
{
a = x; b = y;
}
publicvoiddisplay()
{
[Link]("a={0},b={1}", a, b);
}
}
classClassref
{
staticvoidMain()
{
sample2 s1 = new sample2(3, 4);
sample2 s2;
s2 = s1;
[Link]("before change S1 object");
[Link]();
variable, you also provide a custom constructor. Here is the complete definition of the
Rectangle type:/*
Struct Rectangle
{
// The Rectangle structure contains a reference type member.
publicShapeInfo rectInfo;
public intrectTop, rectLeft, rectBottom, rectRight;
public Rectangle(string info, int top, int left, int bottom, int right)
{
rectInfo = newShapeInfo(info);
rectTop = top; rectBottom = bottom;
rectLeft = left; rectRight = right;
}
Public void Display()
{
[Link]("String = {0}, Top = {1}, Bottom = {2}, " +
"Left = {3}, Right = {4}",
[Link], rectTop, rectBottom, rectLeft, rectRight);
}
}
classVR2
{
Static void Main()
{
Rectangle r1 = newRectangle("this is rectangle",10,10,5,5);
Rectangle r2 = r1;
[Link] = "this is new string";
[Link] = 12;
[Link]();
[Link]();
}
}
}
As you can see, when you change the value of the informational string using the r2 reference,
the r1 reference displays the same value. By default, when a value type contains other
reference types, assignment results in a copy of the references.
The Stack is more or less responsible for keeping track of what's executing in our code (or
what's been "called").
The Heap is more or less responsible for keeping track of our objects.
Think of the Stack as a series of boxes stacked one on top of the next. We keep track of
what's going on in our application by stacking another box on top every time we call a
method.
We can only use what's in the top box on the stack. When we're done with the top box (the
method is done executing) we throw it away and proceed to use the stuff in the previous box
on the top of the stack.
The Heap is similar except that its purpose is to hold information (not keep track of execution
most of the time) so anything in our Heap can be accessed at any time.
With the Heap, there are no constraints as to what can be accessed like in the stack.
The Stack is self-maintaining, meaning that it basically takes care of its own memory
management. When the top box is no longer used, it's thrown out.
The Heap, on the other hand, has to worry about Garbage collection (GC) - which deals with
how to keep the Heap clean .
Value Types
In C#, all the "things" declared with the following list of type declarations are Value types
bool
byte
char
decimal
double
enum
float
int
long
sbyte
short
struct
uint
ulong
ushort
Reference Types
All the "things" declared with the types in this list are Reference types
class
interface
delegate
object
string
Pointers
The third type of "thing" to be put in our memory management scheme is a Reference to a
Type. A Reference is often referred to as a Pointer.
We don't explicitly use Pointers, they are managed by the Common Language Runtime (CLR).
Once we start executing the method, the method's parameters are placed on the stack
As the method executes, we need some memory for the "result" variable and it is allocated on
the stack.
And all memory allocated on the stack is cleaned up by moving a pointer to the available
memory address where AddFive() started and we go down to the previous method on the
stack (not seen here).
Remember the rule, Value Types always go where they were declared? Well, if a Value
Type is declared outside of a method, but inside a Reference Type, it will be placed within
the Reference Type on the Heap.
Here's another example.
If we have the following MyInt class (which is a Reference Type because it is a class):
After AddFive() is finished executing (like in the first example), and we are cleaning up...
we're left with an orphaned MyInt in the heap (there is no longer anyone in the Stack standing
around pointing to MyInt)!
This is where the Garbage Collection (GC) comes into play. Once our program reaches a
certain memory threshold and we need more Heap space, our GC will kick-off.
When we are using Reference Types, we're dealing with Pointers to the type, not the thing
itself. When we're using Value Types, we're using the thing itself.
Again, this is best described by example.
What do we get?... 4!
Why?... How does [Link] get to be 4?... Take a look at what we're doing and see if it
makes sense:
In the next example, we don't get "3" because of both variables "x" and "y" point to the same object
in the Heap.
Parameters
When we make a method call here's what happens:
1. Space is allocated for information needed for the execution of our method on the stack
(called a Stack Frame). This includes the calling address (a pointer) which is basically
a GOTO instruction so when the thread finishes running our method it knows where
to go back to in order to continue execution.
2. Our method parameters are copied over. This is what we want to look at more closely.
1. class Class1
2. {
3. public void Go()
4. {
5. int x = 5;
6. AddFive(x);
7. [Link]([Link]());
8. }
9. public int AddFive(int pValue)
10. {
11. pValue += 5;
12. return pValue;
13. }
14. }
As the method executes, space for "x" is placed on the stack with a value of 5.
Next, AddFive() is placed on the stack with space for it's parameters and the value is copied, bit by bit
from x.
When AddFive() has finished execution, the thread is passed back to Go() and because AddFive() has
completed, pValue is essentially "removed":
1. Starting with the call to Go() the variable x goes on the stack.
2. Starting with the call to DoSomething() the parameter pValue goes on the stack.
3. The value of x (the address of MyInt on the stack) is copied to pValue
So it makes sense that when we change the MyValue property of the MyInt object in the heap
using pValue and we later refer to the object on the heap using x, we get the value "12345".
How
Memory is
Manages?
Practical
Scenario
Memory
Memory allocation is Static Memory allocation is Dynamic
Allocation
How is it
It is stored Directly It is stored indirectly
Stored?
Is Variable
Variables can’t be Resized Variables can be Resized
Resized?
Access
Its access is fast Its access is Slow
Speed
Its block allocation is reserved in
How is Block LIFO. Its block allocation is free and done at
Allocated? Most recently reserved block is any time
always the next block to be freed.
Visibility or It can be visible/accessible only to It can be visible/accessible to all the
Accessibility the Owner Thread threads
It can be used by one thread of It can be used by all the parts of the
Used By?
execution application
When wiped Local variables get wiped off once
-
off? they lose the scope
It is a special thread created by .NET
runtime to monitor allocations of heap
Garbage
- space.
Collector
It only collects heap memory since
objects are only created in heap
UNIT-III
Object oriented programming and Exception Handling
Classes and objects:
Everything in C# is associated with classes and objects, along with its attributes and
methods.
For example: in real life, a car is an object. The car has attributes, such as weight and
color, and methods, such as drive and brake.
A Class is like a "blueprint" for creating objects.
Creating class:
To create a class, use the class keyword:
Create a class named "Car" with a variable color:
class Car
{
string color = "red";
}
When a variable is declared directly in a class, it is often referred to as a field (or
attribute).
Creating object:
An object is created from a class. We have already created the class named Car, so now
we can use this to create objects.
To create an object of Car, specify the class name, followed by the object name, and use
the keyword new:
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj1 = new Car();
Car myObj2 = new Car();
[Link]([Link]);
[Link]([Link]);
}
}
Constructors:
constructor is a special method that is used to initialize objects. The advantage of a
constructor, is that it is called when an object of a class is created. It can be used to set
initial values for fields
using System;
namespace DefaultConstractor
{
class addition
{
int a, b;
public addition() //default contructor
{
a = 100;
b = 175;
}
public static void Main()
{
addition obj = new addition(); //an object is created , constructor is called
[Link](obj.a);
[Link](obj.b);
[Link]();
}
}
}
Parameterized Constructor in C#
using System;
namespace Constructor
{
class paraconstrctor
{
public int a, b;
public paraconstrctor(int x, int y) // decalaring Paremetrized Constructor with ing x,y
parameter
{
a = x;
b = y;
}
}
class MainClass
{
static void Main()
{
paraconstrctor v = new paraconstrctor(100, 175); // Creating object of
Parameterized Constructor and ing values
[Link]("-----------parameterized constructor example --------―);
[Link]("\t");
[Link]("value of a=" + v.a );
[Link]("value of b=" + v.b);
[Link]();
}
}
}
this keyword:
C# supplies a this keyword that provides access to the current class instance
One possible use of the this keyword is to resolve scope ambiguity, which can arise when an
incoming parameter is named identically to a data field of the [Link];
usingSystem;
classStudent{
publicint id, age;
publicString name, subject;
classStudentDetails{
publicstaticvoidMain(string[] args){
Student std1 =newStudent(001,"Jack",23,"Maths");
Student std2 =newStudent(002,"Harry",27,"Science");
Student std3 =newStudent(003,"Steve",23,"Programming");
Student std4 =newStudent(004,"David",27,"English");
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Constructor chaining:
Constructor Chaining is an approach where a constructor calls another constructor in
the same or base class.
Using the keyword ―this‖
using System;
using [Link];
using [Link];
namespace firstsolution
{
public class mySampleClass
{
public mySampleClass() : this(10)
{
// No parameter constructor method.// First Constructor
[Link]("no parameters");
}
public mySampleClass(int Age)
{
Static fields in a non-static class can be defined using the static keyword.
public class StopWatch
{
public static int InstanceCounter = 0;
// instance constructor
public StopWatch()
{
}
}
Static Methods
You can define one or more static methods in a non-static class.
Static methods can be called without creating an object.
You cannot call static methods using an object of the non-static class.
The static methods can only call other static methods and access static members.
You cannot access non-static members of the class in the static methods.
Static Constructors:
A non-static class can contain a parameterless static constructor. It can be
defined with the static keyword and without access modifiers like public, private,
and protected.
using System;
using [Link];
using [Link];
namespace firstsolution
{
class demo2
{
static demo2()
{
[Link]("in static constructor");
}
public demo2()
{
[Link]("in non- static constructor");
}
}
class Class8
{
static void Main()
{
demo2 d = new demo2();
} }
OUTPUT:
in static constructor
in non- static constructor
[<modifier>] type<Name>
{
[get {stmts}]//get accessor
[set {stmts}]//set accessor
}
Ex: public int xproperty
{
get{ return x;}
set{x=value}
}
namespace firstsolution
{
public class customer1
{
int _custid;
bool _status;
string _custname,_state;
double _balance;
cities _city;
public customer1(int custid, bool status, string custname, double balance,cities
city,string state)
{
_custid = custid;
_status = status;
_custname = custname;
_balance = balance;
_city = city;
_state = state;
}
public int custid
{
get { return _custid; }
}
public bool status
{
get { return _status; }
set { _status = value; }
}
In C#, it is possible to inherit fields and methods from one class to another. We group the
"inheritance concept" into two categories:
Derived Class (child) - the class that inherits from another class
Base Class (parent) - the class being inherited from
using System;
namespace firstsolution
{
class ABC
{
public void display()
{
[Link]("parent class display");
}
}
class inheritance:ABC
{
public new void display()
{
[Link]("child class display");
}
static void Main()
{
inheritance i = new inheritance();
ABC a = i;
[Link]();
}
}
}
Polymorphism:
Static Polymorphism
The mechanism of linking a function with an object during compile time is called early
binding. It is also called static binding. C# provides two techniques to implement static
polymorphism. They are −
Function overloading
Operator overloading
Function Overloading
You can have multiple definitions for the same function name in the same scope. The
definition of the function must differ from each other by the types and/or the number of
arguments in the argument list. You cannot overload function declarations that differ only
by return type.
The following example shows using function print() to print different data types −
using System;
namespace PolymorphismApplication {
class Printdata {
void print(int i) {
[Link]("Printing int: {0}", i );
}
void print(double f) {
[Link]("Printing float: {0}" , f);
}
void print(string s) {
[Link]("Printing string: {0}", s);
}
static void Main(string[] args) {
Printing int: 5
Printing float: 500.263
Printing string: Hello C#
Operator overloading
You can redefine or overload most of the built-in operators available in C#. Thus a
programmer can use operators with user-defined types as well. Overloaded operators are
functions with special names the keyword operator followed by the symbol for the operator
being defined. similar to any other function, an overloaded operator has a return type and a
parameter list.
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace firstsolution
{
class Mat
{
public int a, b, c, d;
public Mat(int a, int b, int c, int d)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public static Mat operator+(Mat obj1,Mat obj2)
{
Mat obj = new Mat(obj1.a + obj2.a, obj1.b + obj2.b, obj1.c + obj2.c, obj1.d + obj2.d);
return obj;
}
public static Mat operator -(Mat obj1, Mat obj2)
{
Mat obj = new Mat(obj1.a - obj2.a, obj1.b - obj2.b, obj1.c - obj2.c, obj1.d - obj2.d);
return obj;
}
}
class Class11
{
static void Main()
{
Mat m1 = new Mat(20, 18, 16, 14);
Mat m2 = new Mat(10, 8, 6, 4);
Mat m3 = m1 + m2;
Mat m4 = m1 - m2;
[Link]("the resultant matrix is\n");
[Link](m3.a + " " + m3.b + "\n" + m3.c + " " + m3.d);
[Link]("the resultant matrix is");
[Link]("\n"+m4.a + " " + m4.b + "\n" + m4.c + " " + m4.d);
}
}
}
Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial class implementation
of an interface. Implementation is completed when a derived class inherits from
it. Abstract classes contain abstract methods, which are implemented by the derived class.
The derived classes have more specialized functionality.
Here are the rules about abstract classes −
You cannot create an instance of an abstract class
You cannot declare an abstract method outside an abstract class
When a class is declared sealed, it cannot be inherited, abstract classes cannot be
declared sealed.
The following program demonstrates an abstract class −
Live Demo
using System;
namespace PolymorphismApplication {
abstract class Shape {
public abstract int area();
}
Dynamic polymorphism:
When you have a function defined in a class that you want to be implemented in an inherited
class(es), you use virtual functions. The virtual functions could be implemented differently in
different inherited class and the call to these functions will be decided at runtime.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
The Override keyword is used in the derived class of the base class in order to override the
base class method.
The following program demonstrates this −
using System;
namespace PolymorphismApplication {
class Shape {
protected int width, height;
public Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
public virtual int area() {
[Link]("Parent class area :");
return 0;
}
}
class Rectangle: Shape {
public Rectangle( int a = 0, int b = 0): base(a, b) {
}
public override int area () {
[Link]("Rectangle class area :");
return (width * height);
}
}
class Triangle: Shape {
public Triangle(int a = 0, int b = 0): base(a, b) {
}
public override int area() {
[Link]("Triangle class area :");
return (width * height / 2);
}
}
class Caller {
public void CallArea(Shape sh) {
int a;
a = [Link]();
[Link]("Area: {0}", a);
}
}
class Tester {
static void Main(string[] args) {
Caller c = new Caller();
Rectangle r = new Rectangle(10, 7);
Triangle t = new Triangle(10, 5);
[Link](r);
[Link](t);
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result −
namespace firstsolution
{
class ShapeInfo
{
public string infoString;
public ShapeInfo(string info)
{
infoString = info;
}
}
struct Rectangle
{
// The Rectangle structure contains a reference type member.
public ShapeInfo rectInfo;
public int rectTop, rectLeft, rectBottom, rectRight;
public Rectangle(string info, int top, int left, int bottom, int right)
{
rectInfo = new ShapeInfo(info);
rectTop = top; rectBottom = bottom;
rectLeft = left; rectRight = right;
}
public void Display()
{
[Link]("String = {0}, Top = {1}, Bottom = {2}, " +
"Left = {3}, Right = {4}",
Here the assignment of one object reference variable to another didn't create any memory,
they will refer to the same object. In other words, any copy of the object is not created, but
the copy of the reference is created.
For example, obj1 = obj;
The above line of code just defines that obj1 is referring to the object, obj is referring. So,
when you make changes to object using obj1 will also affect the object obj.
Exception Handling:
An exception is a problem that arises during the execution of a program.
C# exception handling is built upon four keywords: try, catch, finally, and throw.
• try − A try block identifies a block of code for which particular exceptions is
activated. It is followed by one or more catch blocks.
• catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
• finally − The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.
• C# exceptions are represented by classes.
• The exception classes in C# are mainly directly or indirectly derived from
the [Link] class
• Some of the exception classes derived from the [Link] class are
the [Link] and [Link] classes.
• The [Link] class supports exceptions generated by
application programs. Hence the exceptions defined by the programmers should
derive from this class.
• The [Link] class is the base class for all predefined system
exception.
try..catch..finally
C# provides three keywords try, catch and finally to implement exception handling.
The try encloses the statements that might throw an exception whereas catch handles
an exception if one exists.
The finally can be used for any cleanup work that needs to be done.
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 or a finally block or with both catch and finally blocks.
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 100/x;
[Link](div);
}
class MyClient
{
public static void Main()
{
int x = 0;+==
int div = 0;
try
{
div = 100 / x;
[Link]("This linein not executed");
}
catch (DivideByZeroException)
{
[Link]("Exception occured");
}
[Link]($"Result is {div}");
}
}
In c#, the throw is a keyword and it is useful to throw an exception manually during
the execution of the program and we can handle those thrown exceptions using try-
catch blocks based on our requirements.
Dept. of Information Technology, MRCET Page 21
Programming for Application Development (R18) IV- I Sem
The throw keyword will raise only the exceptions that are derived from the Exception
base class.
Following is the syntax of raising an exception using throw keyword in c#.
throw e;
Here, e is an exception that is derived from the Exception class and throw keyword to
throw an exception.
using System;
namespace Exceptions
{
class Program
{
static void Main(string[] args)
{
try
{
GetDetails();
}
catch (Exception ex)
{
[Link]([Link]);
}
[Link]();
}
private static void GetDetails()
{
string name = null;
if ([Link](name))
{
throw new NullReferenceException("Name is Empty");
}
else
{
[Link]("Name: " + name);
}
}
}
}
If you observe the above example, the GetDetails() method will throw
NullReferenceException using throw keyword whenever the name variable value is empty or
null.
Here, we used a new keyword in throw statement to create an object of valid exception type
and we used a try-catch block in method caller to handle thrown exception.
When we execute the above example, we will get the result as shown below.
Name is Empty.
Dept. of Information Technology, MRCET Page 22
Programming for Application Development (R18) IV- I Sem
Exception Properties:
The StackTrace Property :
The [Link] property allows you to identify the series of calls that
resulted in the exception.
The HelpLink Property :
The HelpLink property can be set to point the user to a specific URL or standard Windows
help file that contains more detailed information.
By default, the value managed by the HelpLink property is an empty string.
The Data Property :
The Data property of [Link] allows you to fill an exception object with relevant
auxiliary information (such as a time stamp)
. The Data property returns an object implementing an interface named IDictionary, defined
in the [Link] namespace.
using System;
namespace Exceptions
{
class Exceptionproperties
{
static void Main(string[] args)
{
int a, b, c;
[Link]("ENTER ANY TWO NUBERS");
try
{
a = [Link]([Link]());
b = [Link]([Link]());
c = a / b;
[Link]("C VALUE = " + c);
}
catch (DivideByZeroException dbze)
{
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link] = "[Link]
}
catch (FormatException fe)
{
[Link](" Exception Cause", "Number is not integer");
UNIT-IV
DELEGATES AND ASSEMBLIES
UNDERSTANDING .NET DELEGATE TYPE:
C# delegates are similar to pointers to functions, in C or C++.
A delegate is a reference type variable that holds the reference to a method. The
reference can be changed at runtime.
Delegates are especially used for implementing events and the call-back methods.
All delegates are implicitly derived from the System. Delegate class.
Declaring Delegates
• Delegate declaration determines the methods that can be referenced by the delegate.
• A delegate can refer to a method, which has the same signature as that of the delegate.
• Syntax for delegate declaration is −
• <access specifier>delegate <return type><delegate-name><parameter list>
For example, consider a delegate −
public delegate int MyDelegate (string s);
The preceding delegate can be used to reference any method that has a single string
parameter and returns an int type variable.
Instantiating Delegates:
MyDelegate del = new MyDelegate(MethodA);
// or
MyDelegate del = MethodA;
Invoke a Delegate
A delegate can be invoked using the Invoke() method Or using the () operator.
Example: Invoke a Delegate
[Link]("Hello World!");
// or
del("Hello World!");
class Program
{
public void addnums(int a, int b)
{
[Link](a + b);
}
public static string sayhello(string name)
{
return "HELLO" + name;
}
static void Main(string[] args)
{
Program p = new Program();
adddelegate ad = new adddelegate([Link]);
//adddelegate ad1 = [Link];
saydelegate sd = new saydelegate(sayhello);
//ad(100, 50);
[Link](100, 50);
//String str =sd("MRCET");
String str=[Link]("MRCET");
[Link](str);
}
}
}
Output:
150
HELLOMRCET
MULTICAST DELEGATES:
A Multicast Delegate is a delegate that holds the references of more than one function.
When we invoke the multicast delegate, then all the functions which are referenced by the
delegate are going to be invoked.
If you want to call multiple methods using a delegate then all the method signature should be
the same.
using System;
namespace Delegates
{
public delegate void rectdelegate(double width, double height);
class Rectangle
{
public void getarea(double width,double height)
{
[Link]("Area of rectangle" + (width * height));
}
public void getperimeter(double width, double height)
{
[Link]("perimeter of rectangle" + (2*(width+height)));
}
static void Main()
{
Rectangle rect = new Rectangle();
rectdelegate obj = [Link];
// obj = obj + [Link];
obj+= [Link];
[Link](12.34, 56.38);
//obj = obj - [Link];
obj -= [Link];
[Link](12.34, 56.38);
}
}
}
Output:
Area of rectangle695.7292
perimeter of rectangle137.44
Area of rectangle695.7292
Namespaces in C# are used to organize too many classes so that it can be easy to handle the
application.
In a simple C# program, we use [Link] where System is the namespace and Console
is the class. To access the class of a namespace, we need to use [Link].
We can use using keyword so that we don't have to use complete name all the time.
A namespace definition begins with the keyword namespace followed by the namespace
name as follows
namespace namespace_name {
// code declarations
}
To call the namespace-enabled version of either function or variable, prepend the namespace
name as follows −
namespace_name.item_name;
namespace first_space {
class namespace_cl {
publicvoid func(){
[Link]("Inside first_space");
}
}
}
namespace second_space {
class namespace_cl {
publicvoid func(){
[Link]("Inside second_space");
}
}
}
classTestClass{
staticvoidMain(string[] args){
first_space.namespace_cl fc =new first_space.namespace_cl();
second_space.namespace_cl sc =new second_space.namespace_cl();
[Link]();
[Link]();
[Link]();
}
}
When the above code is compiled and executed, it produces the following result −
Inside first_space
Inside second_space
The using keyword states that the program is using the names in the given namespace. For
example, we are using the System namespace in our programs. The class Console is defined
there. We just write −
[Link] ("Hello there");
We could have written the fully qualified name as
[Link]("Hello there");
You can also avoid prepending of namespaces with the using namespace directive. This
directive tells the compiler that the subsequent code is making use of names in the specified
namespace
.NET Assembly:
The .NET assembly is the standard for components developed with the [Link].
. NET assemblies may or may not be executable, i.e., they might exist as the executable (.exe)
file or dynamic link library (DLL) file.
All the standard library files are saved as .dll and userdefined files are saved with .exe
extension.
We cannot execute .dll file unlike .exe rather we have to consume them in some other file to
execute them.
.NET supports two kinds of assemblies:
private
Shared
Private Assembly
Private assembly requires us to copy separately in all application folders where we want to
use that assembly’s functionalities; without copying, we cannot access the private assembly
features and power.
Private assembly means every time we have one, we exclusively copy into the BIN folder of
each application folder.
Private assembly requires us to copy separately in all application folders where we want to
use that assembly’s functionalities; without copying, we cannot access the private assembly
features and power. Private assembly means every time we have one, we exclusively copy
into the BIN folder of each application folder.
Public Assembly:
Public assembly is not required to copy separately into all application folders.
Public assembly is also called Shared Assembly.
Only one copy is required in system level, there is no need to copy the assembly into the
application folder.
Public assembly should install in GAC.
GAC (Global Assembly Cache):
• When the assembly is required for more than one project or application, we need to
make the assembly with a strong name and keep it in GAC or in the Assembly folder
by installing the assembly with the gacutil -i command.
Configuring assemblies:
• Creating private assembly:
• Open visualstudio->create a new project-> select class library->next->give some
name(mydll)->create some method under a class without main->build->build solution
• Open visualstudio->create a new project-> select console application->next->give
some name(mydll)-> right click solution->add->project reference>browse->c:-
>windows->Microsoft .net->assembly->GAC_MSIL->select mydll->[Link]
• Now, we can use the method declared in .dll file
Configuring assemblies-creating public assemblies
• Open visualstudio->create a new project-> select class library->next->give some
name(mydll)->create some method under a class without main->project tab->
projectname properties->signing->sign the assembly->choose a strong name key file-
>new->give some file name->ok->build
For Eg:
UNIT-V
[Link]
[Link] stands for ActiveX Data Object is a database access technology created by
Microsoft as part of its .NET framework that can access any kind of data source.
It’s a set of object-oriented classes that provides a rich set of data components to create
database applications for client- server applications as well as distributed environments over
the Internet and intranets.
Although the specific names of these core classes will differ among data providers (e.g.,
SqlConnection vs. OracleConnection vs. OdbcConnection vs. MySqlConnection), each class
derives from the same base class (DbConnection, in the case of connection objects) that
implements identical interfaces (e.g., IDbConnection)
Figure 21-2 shows the big picture behind [Link] data providers. Note how the diagram
illustrates that the Client Assembly can literally be any type of .NET application: console
program, Windows Forms application, WPF application, [Link] web page, WCF service,
a .NET code library, and so on.
A data provider will supply you with other types beyond the objects shown in Figure 21-2;
however, these core objects define a common baseline across all data providers.
The Microsoft-Supplied [Link] Data Providers
For example, consider the following simple C# Console Application project (named
MyConnectionFactory), which allows you to obtain a specific connection object based on the
value of a custom enumeration
namespace MyConnectionFactory
{
// A list of possible providers.
enum DataProvider
{ SqlServer, OleDb, Odbc, None }
class Program
{
static void Main(string[] args)
{
[Link]("**** Very Simple Connection Factory *****\n");
// Get a specific connection.
IDbConnection myCn = GetConnection([Link]);
[Link]("Your connection is a {0}", [Link]().Name);
// Open, use and close connection...
[Link]();
}
// This method returns a specific connection object
// based on the value of a DataProvider enum.
static IDbConnection GetConnection(DataProvider dp)
{
IDbConnection conn = null;
switch (dp)
{
case [Link]:
conn = new SqlConnection();
break;
case [Link]:
conn = new OleDbConnection();
break;
case [Link]:
conn = new OdbcConnection();
break;
}
return conn;
}
}
}
At this point, the AutoLot database is empty of any database objects (e.g., tables and stored
procedures). To insert a new database table, right-click the Tables node and select Add New
Table (see Figure 21-4)
Use the table editor to add four columns (CarID, Make, Color, and PetName). Ensure that the
CarID column has been set to the Primary Key (do this by right-clicking the CarID row and
selecting Set Primary Key). Figure 21-5 shows the final table settings (you don’t need to
change anything in the Column Properties editor, but you should notice the data types for
each column).
Save (and then close) your new table; also, be sure you name this new database object
Inventory. At this point, you should see the Inventory table under the Tables node of the
Server Explorer. Right-click the Inventory table icon and select Show Table Data
class program
{
static void Main()
{
sqlconnection con;
con= new sqlconnection("path to the database");
[Link]();
string starsql="select * from Employee";
sqlcommand mycommand=new sqlcommand(starsql,"con");
sqldatareader mydatareader;
mydatareader=[Link]();
while([Link]())
{
----
----
}
[Link]();
}
[Link]();
// Create a SQL command object.
string strSQL = "Select * From Inventory";
SqlCommand myCommand = new SqlCommand(strSQL, cn);
// Obtain a data reader a la ExecuteReader().
using(SqlDataReader myDataReader = [Link]())
{
// Loop over the results.
while ([Link]())
{
[Link]("-> Make: {0}, PetName: {1}, Color: {2}.",
myDataReader["Make"].ToString(),
myDataReader["PetName"].ToString(),
myDataReader["Color"].ToString());
}
}
}
[Link]();
}
}
Data readers are useful when you need to iterate over large amounts of data quickly and you
do not need to maintain an in-memory representation
You obtain data reader objects from the command object using a call to ExecuteReader().
The data reader represents the current record it has read from the database. The data reader
has an indexer method (e.g, [] syntax in C#) that allows you to access a column in the current
record.
You can access the column either by name or by zero-based integer.
The following use of the data reader leverages the Read() method to determine when you
have
reached the end of your records (using a false return value). For each incoming record that
you read
from the database, you use the type indexer to print out the make, pet name, and color of each
automobile. Also note that you call Close() as soon as you finish processing the records; this
frees up theconnection object:
static void Main(string[] args)
{
...
// Obtain a data reader via ExecuteReader().
using(SqlDataReader myDataReader = [Link]())
{
// Loop over the results.
while ([Link]())
{
[Link]("-> Make: {0}, PetName: {1}, Color: {2}.",
myDataReader["Make"].ToString(),
myDataReader["PetName"].ToString(),
myDataReader["Color"].ToString());
}
}
[Link]();
}
Connection
DataAdapter
DataSet
Connection: Connection class uses to establish the connection between the front end and
back end.
DataSet: DataSet contains the tables and relationships as in the following figure:
DataAdapter does not have a feature of containing data so there is a dataset that contains
table and relation after generating result set.
Syntax for DataSet is:
DataSet ds=new DataSet();
[Link](ds,”X”);
The architecture of connectionless is as in the following figure:
Client-side interacts with server-side through [Link] because the front end application
will not understand the syntax of back end application so there is [Link] which is a group
of classes that contain Connection, Command, DataAdapter, and DataSet.