Documente Academic
Documente Profesional
Documente Cultură
Introduction to .NET
.Net Definition
What does .NET Framework (.NET) mean?
The .NET framework is a software development framework from Microsoft. It provides a controlled
programming environment where software can be developed, installed and executed on Windows-based
operating systems.
Advantages of .NET:
Object Oriented
Everything that you see in the .NET framework is an object. It is the same for what you write within the
framework. This means that you get a powerful tool to not just access but also control your apps. This
also makes it simpler for you to respond to recurring events.
Caching
The caching system that .NET includes is extremely robust and easy-to-use.
Easy Maintenance
Pages, with .NET, are extremely simple to write and maintain. This is because the source code and
HTML are both together. In addition to that, the source code executes on the server. What does this
mean? This makes your web pages more powerful and flexible.
Time-Saving
Time is money, and .NET helps you save a lot of that. The way it is developed, .NET removes a large
part of the coding requirement. This means that the developers save time, and the app’s time-to-market
can be shortened considerably.
Simplicity
Performing common tasks with .NET is extremely simple and straight forward. Submission of forms is a
breeze and so is site configuration, deployment, and client authentication.
Feature-Rich
There are a range of features that can be explored by the developers in order to create powerful apps.
Consider the case of its rich toolbox as also the designer in the visual studio. They let you access such
features as automatic deployment, WYSIWYG editing, and drag-and-drop controls.
Monitoring
Finally, .NET also stands for its automatic monitoring. It will promptly notice any problems like infinite
loops, memory leaks, etc. Not just this, it will also destroy these activities automatically and restart itself.
Consistency
The management and monitoring of all the processes is performed by the framework. If one of the
processes is dead, a new process can be created just as easily. This lets your app be consistently
available for handling requests.
.NET Architecture
.NET Components
The architecture of the .Net framework is based on the following key components;
If an application tries to open a file on the local machine, but the file is not present.
If the application tries to fetch some records from a database, but the connection to the database is
not valid.
2. Garbage Collection - Garbage collection is the process of removing unwanted resources when
they are no longer required.
Examples of garbage collection are:
A File handle which is no longer required. If the application has finished all operations on a file, then
the file handle may no longer be required.
The database connection is no longer required. If the application has finished all operations on a
database, then the database connection may no longer be required.
3. Language - The first level is the programming language itself, the most common ones are VB.Net
and C#.
4. Compiler – There is a compiler which will be separate for each programming language. So
underlying the VB.Net language, there will be a separate VB.Net compiler. Similarly, for C#, you will
have another compiler.
5. Common Language Interpreter – This is the final layer in .Net which would be used to run a .net
program developed in any programming language. So the subsequent compiler will send the
program to the CLI layer to run the .Net application.
C# Basics
Features of C#
Simplicity - All the Syntax of java is like C++. There is no pre-processor and much larger library. C#
code does not require header files. All code is written inline.
Consistent Behaviour - C# introduced a unified type system which eliminates the problem of
varying ranges of integer types. All types are treated as objects and developers can extend the type
system simply and easily.
• Type Safety - Type safety promotes robust programming. Some examples of type safety are:
1. All objects and arrays are initialized by zero dynamically
2. An error message will be produced, on use of any uninitialized variable
3. Automatic checking of array (out of bound and etc.)
• Feature of Versioning - Making new versions of software module work with the existing
applications is known as versioning. It’s achieve by the keywords new and override.
• Compatible with other Language - C# enforces the .NET common language specifications (CLS)
and therefore allows interoperation with other .NET language.
C# - Data Types
The variables in C#, are categorized into the following types:
• Value types
• Reference types
• Pointer types
• Value Type
• Value type
1. Variables can be assigned a value directly. They are derived from the class System.ValueType.
2. The value types directly contain data. Some examples are int, char, and float, which stores
numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the
system allocates memory to store the value.
• Reference Type
1. The reference types do not contain the actual data stored in a variable, but they contain a reference
to the variables.
2. In other words, they refer to a memory location. Using multiple variables, the reference types can
refer to a memory location. If the data in the memory location is changed by one of the variables,
the other variable automatically reflects this change in value. Example of built-in reference types
are: object, dynamic, and string.
• Pointer Type
1. Pointer type variables store the memory address of another type. Pointers in C# have the same
capabilities as the pointers in C or C++.
2. Syntax for declaring a pointer type is − type* identifier;
For example:
char* cptr;
int* iptr;
C# Flow Control
http://zetcode.com/lang/csharp/flowcontrol/
Go through this once
Main Method in C#
C# applications have an entry point called Main Method. It is the first method which gets invoked whenever
an application started and it is present in every C# executable file. The application may be Console
Application or Windows Application. The most common entry point of a C# program is static void Main() or
static void Main(String [ ]args).
C# - Program Structure
Creating Hello World Program
A C# program consists of the following parts −
Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements and Expressions
Comments
Let us look at a simple code that prints the words "Hello World" − Live Demo
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When this code is compiled and executed, it produces the following result − "Hello World"
Let us look at the various parts of the given program −
The first line of the program using System; the using keyword is used to include the System
namespace in the program. A program generally has multiple using statements.
The next line has the namespace declaration. A namespace is a collection of classes. The
HelloWorldApplication namespace contains the class HelloWorld.
The next line has a class declaration, the class HelloWorld contains the data and method
definitions that your program uses. Classes generally contain multiple methods. Methods define the
behaviour of the class. However, the HelloWorld class has only one method Main.
The next line defines the Main method, which is the entry point for all C# programs. The Main
method states what the class does when executed. i.e., static void Main(string[] args)
The next line /.../ is ignored by the compiler and it is put to add comments in the program.
The Main method specifies its behavior with the statement Console.WriteLine("Hello World");
WriteLine is a method of the Console class defined in the System namespace. This statement
causes the message "Hello, World!" to be displayed on the screen.
The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key
press and it prevents the screen from running and closing quickly when the program is launched
from Visual Studio .NET.
C# - Methods
A method is a group of statements that together perform a task. Every C# program has at least one class
with a method named Main.
To use a method, you need to −
Defining Methods in C# - When you define a method, you basically declare the elements of its
structure. The syntax for defining a method in C# is as follows −
<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
Method Body
}
Calling Methods in C#
You can call a method using the name of the method. The following example illustrates this − Live Demo
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Declaring Arrays
To declare an array in C#, you can use the following syntax −
datatype[] arrayName;
where,
datatype is used to specify the type of elements in the array.
[ ] specifies the rank of the array. The rank specifies the size of the array.
arrayName specifies the name of the array.
For example,
double[] balance;
Initializing an Array
Declaring an array does not initialize the array in the memory. When the array variable is initialized, you
can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array. For
example,
You can assign values to the array at the time of declaration, as shown −
double[] balance = { 2340.0, 4523.69, 3421.0};
C# - Namespaces
A namespace is designed for providing a way to keep one set of names separate from another. The class
names declared in one namespace does not conflict with the same class names declared in another.
Defining a Namespace
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;
Chapter 3
Object Oriented C#
Object Oriented Programming in C#
C# provides full support for object-oriented programming including encapsulation, inheritance, and
polymorphism.
Object-oriented programming (OOP) is the core ingredient of the .NET framework. OOP is so
important that, before embarking on the road to .NET, you must understand its basic principles and
terminology to write even a simple program. The fundamental idea behind OOP is to combine into a
single unit both data and the methods that operate on that data; such units are called an object. All
OOP languages provide mechanisms that help you implement the object-oriented model.
Encapsulation means that a group of related properties, methods, and other members are treated
as a single unit or object.
Inheritance describes the ability to create new classes based on an existing class.
Polymorphism means that you can have multiple classes that can be used interchangeably, even
though each class implements the same properties or methods in different ways.
Object, in C#, is an instance of a class that is created dynamically. Object is also a keyword that is an alias
for the predefined type System.Object in the .NET framework.
Inheritance
One of the most important concepts in object-oriented programming is inheritance. Inheritance
allows us to define a class in terms of another class, which makes it easier to create and maintain
an application. This also provides an opportunity to reuse the code functionality and speeds up
implementation time.
When creating a class, instead of writing completely new data members and member functions, the
programmer can designate that the new class should inherit the members of an existing class. This
existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog
IS-A mammal hence dog IS-A animal as well, and so on.
Multiple Inheritance in C#
C# does not support multiple inheritance. However, you can use interfaces to implement multiple
inheritance. The following program demonstrates this − Live Demo
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// Base class PaintCost
public interface PaintCost
{
int getCost(int area);
}
// Derived class
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
public int getCost(int area)
{
return area * 70;
}
}
class RectangleTester
{ static void Main(string[] args)
{ Rectangle Rect = new Rectangle();
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}
Method Overloading
Method Overloading is the common way of implementing polymorphism. It is the ability to redefine a
function in more than one form. A user can implement function overloading by defining two or more
functions in a class sharing the same name. C# can distinguish the methods with different method
signatures. i.e. the methods can have the same name but with different parameters list (i.e. the number of
the parameters, order of the parameters, and data types of the parameters) within the same class.
Example:
class base
{
public void gfg();
}
class derived : base
{
public void gfg();
}
class Main_Method
{
static void Main()
{
derived d = new derived();
d.gfg();
}
}
Here the base class is inherited in derived class and the method gfg() which has the same signature in both
the classes, is overridden.
Notes
Abstract classes and methods are declared with the 'abstract' keyword. Abstract classes can only
be extended, and cannot be directly instantiated.
Abstract classes provide a little more than interfaces. Interfaces do not include fields and super
class methods that get inherited, whereas abstract classes do. This means that an abstract class is
more closely related to a class which extends it, than an interface is to a class that implements it.
Modifiers can only be 'public' or 'protected'. The modifier in the child class overriding a method must
be the same as the modifier in the parent abstract class.
Syntax
modifier abstract class className
{
//declare fields (which can contain assignments)
modifier dataType variableName;
//declare methods
modifier abstract dataType methodName();
}
modifier class childClass : className
{
override modifier dataType methodName()
{
//code
}
}
Example
public abstract class Animal
{
protected string name;
public abstract string sound();
//all classes that implement Animal must have a sound method
}
public class Cat : Animal
{
public Cat()
{
this.name = "Garfield";
}
override public string sound()
{
//implemented sound method from the abstract class & method
return "Meow!";
}
}
Access modifiers
Why to use access modifiers?
Access modifiers are an integral part of object-oriented programming. They support the concept of
encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define who
does or doesn't have access to certain features.
Modifier Description
public There are no restrictions on accessing public members.
private Access is limited to within the class definition. This is the default access modifier
type if none is formally specified
protected Access is limited to within the class definition and any class that inherits from the
class
internal Access is limited exclusively to classes defined within the current project assembly
protected internal Access is limited to the current assembly and types derived from the containing
class. All members in current project and all members in derived class can access
the variables.
Properties
Properties are the special type of class members that provides a flexible mechanism to read, write,
or compute the value of a private field. Properties can be used as if they are public data members,
but they are actually special methods called accessors. This enables data to be accessed easily
and help to promote the flexibility and safety of methods. Encapsulation and hiding of information
can also be achieved using properties. It uses pre-define methods which are “get” and “set”
methods which helps to access and modify the properties.
Accessors: The block of “set” and “get” is known as “Accessors”. It is very essential to restrict the
accessibility of property. There are two type of accessors i.e. get accessors and set accessors.
There are different types of properties based on the “get” and set accessors:
1. Read and Write Properties: When property contains both get and set methods.
2. Read-Only Properties: When property contains only get method.
3. Write Only Properties: When property contains only set method.
The syntax for Defining Properties:
<access_modifier> <return_type> <property_name>
{
get
{
// body
}
set
{
// body
}
}
//Write-only Property
Set Accessor: It will specify the assignment of a value to a private field in a property. It returns a single
value and it specifies the write-only property.
class Geeks
{
// Declare roll_no field
private int roll_no;
// Declare roll_no property
public int Roll_no
{
get
{
return roll_no;
}
set
{
roll_no = value;
}
}
}
Introduction to Functions in C#
In C#, a function is a way of packaging code that does something and then returns the value. Unlike
in C, C++ and some other languages, functions do not exist by themselves. They are part of an
object-oriented approach to programming
In C#, a function can be called a member function—it is a member of a class—but that terminology
is left over from C++. The usual name for it is a method.
A simple example - The code below adds a function, a method that outputs the word "Hello."
using System;
namespace funcex1
{
class Test
{
public void SayHello()
{
Console.WriteLine("Hello") ;
}
class Program
{
static void Main(string[] args)
{
var t = new Test() ;
t.SayHello() ;
Console.ReadKey() ;
}
}
Static Method
Static methods are called without instantiation. This means that static methods can only access other static
members of the class
Syntax
public class className
{
modifier static dataType methodName (inputParameters)
{
//static method
//block of code to be executed
}
}
//calling the method, from anywhere
className.methodName(passedParams);
Example
public class Numbers
{
public Numbers() {}
public static int findMinimum(int number1, int number2)
{
//3 stored in number1, 5 stored in number2
int minimum = number2;
if (number1 < number2) minimum = number1;
return minimum;
}
}
int min = Numbers.findMinimum(3, 5);
C# Interface:
An interface in C# contains only the declaration of the methods, properties, and events, but not the
implementation. It is left to the class that implements the interface by providing implementation for
all the members of the interface. Interface makes it easy to maintain a program.
In C#, an interface can be defined using the interface keyword. For example, the following is a
simple interface for a logging string message:
Interface Declaration:
interface ILog
{
void Log(string msgToLog);
}
1. Now, different classes can implement ILog by providing an implementation of the Log() method, for
example, the ConsoleLog class logs the string on the console whereas FileLog logs the string into a
text file.
Implement interface using <Class Name> : <Interface Name > syntax.
Implement Interface
class ConsoleLog: ILog
{
public void Log(string msgToPrint)
{
Console.WriteLine(msgToPrint);
}
}
class FileLog :ILog
{
public void Log(string msgToPrint)
{
File.AppendText(@"C:\Log.txt").Write(msgToPrint);
}
}
2. Now, you can instantiate an object of either the ConsoleLog or FileLog class:
Instantiate Object
ILog log = new ConsoleLog();
//Or
Dispose method
You implement a Dispose method to release unmanaged resources used by your application.
The .NET garbage collector does not allocate or release unmanaged memory.
The pattern for disposing an object, referred to as a dispose pattern, imposes order on the lifetime
of an object. The dispose pattern is used only for objects that access unmanaged resources, such
as file and pipe handles, registry handles, wait handles, or pointers to blocks of unmanaged
memory. This is because the garbage collector is very efficient at reclaiming unused managed
objects, but it is unable to reclaim unmanaged objects.
Example Program ??
MizzzMeWithGaiiiShitzz
C# Operator Overloading
The concept of overloading a function can also be applied to operators. Operator overloading gives
the ability to use the same operator to do various operations. It provides additional capabilities to C#
operators when they are applied to user-defined data types.
The function of the operator is declared by using the operator keyword.
Syntax:
access specifier className operator Operator_symbol (parameters)
{
// Code
}
Output:
Number1 = -15
Number2 = 25
Chapter 4
Advanced C# Topics
Errors and Exception Handling
Types of Errors
In programming language errors can be divided into three categories as given below-
Syntax Errors
Syntax errors occur during development, when you make type mistake in code. For example,
instead of writing while, you write WHILE then it will be a syntax error since C# is a case sensitive
language.
bool flag=true;
WHILE (flag) //syntax error, since c# is case sensitive
{
//TO DO:
}
int a = 5, b = 0;
int result = a / b; // DivideByZeroException
Logical Errors
Logic errors occur when the program is written fine but it does not produce desired result. Logic
errors are difficult to find because you need to know for sure that the result is wrong
int a = 5, b = 6;
double avg = a + b / 2.0; // logical error, it should be (a + b) / 2.0
Exception Handling
Exception handling is a mechanism to detect and handle run time errors. It is achieved by using Try-Catch-
Finally blocks and throw keyword.
Try block
The try block encloses the statements that might throw an exception.
try
{
// Statements that can cause exception.
}
Catch block
Catch block handles any exception if one exists.
catch(ExceptionType e)
{
// Statements to handle exception.
}
Finally block
The finally block can be used for doing any clean-up process like releasing unused resources even
if an exception is thrown. For example, disposing database connection.
finally
{
// Statement to clean up.
}
Throw keyword
This keyword is used to throw an exception explicitly.
catch (Exception e)
{
throw (e);
}