0% found this document useful (0 votes)
25 views56 pages

AWP Unit 1

ASP.Net class notes

Uploaded by

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

AWP Unit 1

ASP.Net class notes

Uploaded by

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

ASP.

NET
UNIT 1
Chapter 1: Introducing .NET
What is .NET Framework?
• .NET Framework is a software development framework for building and running applications on Windows.
• .NET is a developer platform made up of tools, programming languages, and libraries for building many
different types of applications.
• There are various implementations of .NET. Each implementation allows .NET code to execute in different
places—Linux, macOS, Windows, iOS, Android, and many more.
• .NET Framework is the original implementation of .NET. It supports running websites, services, desktop apps,
and more on Windows.
• .NET is a cross-platform implementation for running websites, services, and console apps on Windows, Linux,
and macOS. .NET is open source on GitHub. .NET was previously called .NET Core.
• Xamarin/Mono is a .NET implementation for running apps on all the major mobile operating systems, including
iOS and Android.
• .NET Standard is a formal specification of the APIs that are common across .NET implementations. This allows
the same code and libraries to run on different implementations.

• Advantages of .NET Framework:


Multi-language support: The .NET Framework supports a variety of programming languages, including C#, F#,
and Visual Basic, which allows developers to choose the language that best fits their needs and expertise.
Cross-platform compatibility: The .NET Framework can run on multiple operating systems, including Windows,
Linux, and macOS, which provides flexibility in developing and deploying applications.
Large community: The .NET Framework has a large and active community of developers who have created a
wide range of resources, including libraries, tools, and documentation.
Security: The .NET Framework includes a variety of security features, such as code access security and digital
signatures, which can help protect applications from malicious attacks.
Productivity: The .NET Framework includes a large set of pre-built libraries and tools that can help developers
save time and improve productivity.

What is C#?
• C# is pronounced "C-Sharp".
• It is an object-oriented programming language created by Microsoft that runs on the .NET Framework.
• C# has roots from the C family, and the language is close to other popular languages like C++ and Java.
• The first version was released in year 2002. The latest version, C# 12, was released in November 2023.
• C# is used for:
• Mobile applications , Desktop applications, Web applications ,Web services, Web sites, Games , VR , Database
applications

• Common Language Runtime (CLR)


• The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the
execution of .NET applications. It is responsible for loading and executing the code written in various .NET
programming languages, including C#, VB.NET, F#, and others.
• Native code is binary data compiled to run on a processor, such as an Intel x86-class processor.
• Suppose you have written a C# program and save it in a file which is known as the Source Code.
• Language specific compiler compiles the source code into the MSIL(Microsoft Intermediate Language) which
is also known as the CIL(Common Intermediate Language) or IL(Intermediate Language) along with its
metadata. Metadata includes all the types, actual implementation of each function of the program. MSIL is
machine-independent code.
• Now CLR comes into existence. CLR provides the services and runtime environment to the MSIL code.
Internally CLR includes the JIT (Just-In-Time) compiler which converts the MSIL code to machine code which
further executed by CPU. CLR also uses the .NET Framework class libraries. Metadata provides information
about the programming language, environment, version, and class libraries to the CLR by which CLR handles
the MSIL code. As CLR is common so it allows an instance of a class that written in a different language to call a
method of the class which written in another language.

The .NET Class Library

• Class library is the second major entity of the .NET framework which is designed to integrate with the common
language runtime.
• It gives the program access to runtime environment.
• It Consists of lots of prewritten code that all the applications created in VB .NET and Visual Studio .NET will use
it.
• The code for all the elements like forms, controls and the rest in VB .NET applications actually comes from the
class library.
• It provides classes that can be used in the code to accomplish a range of common programming tasks, such as
string management, data collection, and database connectivity and file access.
UNIT 1
Chapter 2: The C# Language

C# Language Basics:
• C# (C-Sharp) is a programming language developed by Microsoft that runs on the .NET Framework.
• C# is used to develop web apps, desktop apps, mobile apps, games and much more.

• Example
using System;

namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}

Output:
Hello World!

• Example explained

• Line 1: using System means that we can use classes from the System namespace.
• Line 2: A blank line. C# ignores white space. However, multiple lines makes the code more readable.
• Line 3: namespace is used to organize your code, and it is a container for classes and other namespaces.
• Line 4: The curly braces {} marks the beginning and the end of a block of code.
• Line 5: class is a container for data and methods, which brings functionality to your program. Every line of code
that runs in C# must be inside a class. In our example, we named the class Program.
• Line 7: Another thing that always appear in a C# program is the Main method. Any code inside its curly
brackets {} will be executed. You don't have to understand the keywords before and after Main. You will get to
know them bit by bit while reading this tutorial.
• Line 9: Console is a class of the System namespace, which has a WriteLine() method that is used to
output/print text. In our example, it will output "Hello World!".
• If you omit the using System line, you would have to write System.Console.WriteLine() to print/output text.
• Note: Every C# statement ends with a semicolon ;
• Note: C# is case-sensitive; "MyClass" and "myclass" have different meaning

• C# Output
• To output values or print text in C#, you can use the WriteLine() method:
Example:
Console.WriteLine("Hello World!");

• You can add as many WriteLine() methods as you want. Note that it will add a new line for each method:
Example:
Console.WriteLine("Hello World!");
Console.WriteLine("I am Learning C#");
Console.WriteLine("It is awesome!");
• You can also output numbers, and perform mathematical calculations:
• Example:
Console.WriteLine(3 + 3);

• The Write Method


• There is also a Write() method, which is similar to WriteLine().
• The only difference is that it does not insert a new line at the end of the output:
• Example:
Console.Write("Hello World! ");
Console.Write("I will print on the same line.");

• C# Comments
• Comments can be used to explain C# code, and to make it more readable. It can also be used to prevent
execution when testing alternative code.

1. Single-line Comments
• Single-line comments start with two forward slashes (//).
• Any text between // and the end of the line is ignored by C# (will not be executed).
This example uses a single-line comment before a line of code:
Example:
// This is a comment
Console.WriteLine("Hello World!");

2. C# Multi-line Comments
• Multi-line comments start with /* and ends with */.
• Any text between /* and */ will be ignored by C#.
• This example uses a multi-line comment (a comment block) to explain the code:
Example:
/* The code below will print the words Hello World
to the screen, and it is amazing */
Console.WriteLine("Hello World!");

 C# Variables

Variables are containers for storing data values.

In C#, there are different types of variables (defined with different keywords), for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -123
 double - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
 string - stores text, such as "Hello World". String values are surrounded by double quotes
 bool - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable, you must specify the type and assign it a value:
Syntax:

type variableName = value;

Where type is a C# type (such as int or string), and variableName is the name of the variable (such
as x or name). The equal sign is used to assign values to the variable.
 To create a variable that should store text, look at the following example:

Example
Create a variable called name of type string and assign it the value "John":
string name = "John";
Console.WriteLine(name);

 To create a variable that should store a number, look at the following example:

Example
Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
Console.WriteLine(myNum);

 You can also declare a variable without assigning the value, and assign the value later:
Example
int myNum;
myNum = 15;
Console.WriteLine(myNum);
 Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example
Change the value of myNum to 20:
int myNum = 15;
myNum = 20; // myNum is now 20
Console.WriteLine(myNum);
Other Types
A demonstration of how to declare variables of other types:
int myNum = 5;
double myDoubleNum = 5.99D;
char myLetter = 'D';
bool myBool = true;
string myText = "Hello";

C# Display Variables
The WriteLine() method is often used to display variable values to the console window.
 To combine both text and a variable, use the + character:
Example
string name = "John";
Console.WriteLine("Hello " + name);

 You can also use the + character to add a variable to another variable:
Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
Console.WriteLine(fullName);
 For numeric values, the + character works as a mathematical operator (notice that we use int (integer)
variables here):
Example
int x = 5;
int y = 6;
Console.WriteLine(x + y); // Print the value of x + y

Data Types
 Data types are int, char, float etc.Reference Data Types - These data types contain a reference to the variables
and not the actual data.
Example
int myNum = 5; // Integer (whole number)
double myDoubleNum = 5.99D; // Floating point number
char myLetter = 'D'; // Character
bool myBool = true; // Boolean
string myText = "Hello"; // String

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

Data Type Size


int 4 bytes
long 8 bytes
float 4 bytes
double 8 bytes
bool 1 bit
char 2 bytes
string 2bytes per character

Numbers
Number types are divided into two groups:
Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types
are int and long. Which type you should use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or more decimals. Valid types
are float and double.

Example
int myNum = 100000;
Console.WriteLine(myNum);

Integer Types
Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial,
the int data type is the preferred data type when we create variables with a numeric value.
int myNum = 100000;
Console.WriteLine(myNum);
Long
The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is
used when int is not large enough to store the value. Note that you should end the value with an "L":
long myNum = 15000000000L;
Console.WriteLine(myNum);
Floating Point Types
You should use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515.
The float and double data types can store fractional numbers. Note that you should end the value with an "F"
for floats and "D" for doubles:
float myNum = 5.75F;
Console.WriteLine(myNum);

double myNum = 19.99D;


Console.WriteLine(myNum);
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
Program:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
float f1 = 35e3F;
double d1 = 12E4D;
Console.WriteLine(f1);
Console.WriteLine(d1);
}
}
}

Output:
5000
120000

A Boolean data type is declared with the bool keyword and can only take the values true or false:
bool isCSharpFun = true;
bool isFishTasty = false;
Console.WriteLine(isCSharpFun); // Outputs True
Console.WriteLine(isFishTasty); // Outputs False

The char data type is used to store a single character. The character must be surrounded by single quotes, like
'A' or 'c':
char myGrade = 'B';
Console.WriteLine (myGrade);

The string data type is used to store a sequence of characters (text). String values must be surrounded by
double quotes:
string greeting = "Hello World";
Console.WriteLine(greeting);
Variable Operations
In C#, you can perform various operations on variables depending on their data types. Here are some examples:
1. Arithmetic Operations
You can perform arithmetic operations on numeric variables such as int, float, and double. Some of the arithmetic
operators supported in C# are:

Operator Description Example

+ Addition 1+1=2

– Subtraction 5–2=3

* Multiplcation 2 * 5 = 10

/ Division 5.0 / 2 = 2.5

% Mod 200 % 4 = 8

Arithmetic Operators
These are operators used for performing mathematic operations on numbers. Below is the list of operators available
in C#.
Operator Description
+ Adds two operands
– Subtracts the second operand from the first
* Multiplies both operands
/ Divides the numerator by de-numerator
% Modulus Operator and a remainder of after an integer division
++ Increment operator increases integer value by one
— Decrement operator decreases integer value by one

Relational Operators
These are operators used for performing Relational operations on numbers. Below is the list of relational operators
available in C#.
Operator Description
== Checks if the values of two operands are equal or not, if yes then condition becomes true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition become
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes tr

Logical Operators
These are operators used for performing Logical operations on values. Below is the list of operators available in C#.
Operator Description
&& This is the Logical AND operator. If both the operands are true, then condition becomes true.
|| This is the Logical OR operator. If any of the operands are true, then condition becomes true.
! This is the Logical NOT operator.
Let’s look at a quick example of how the operators can be used in .Net.
In our example, we will define 2 Integer variables and one Boolean variable. We will then perform the following
operations
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
class Program
{
static void Main(string[] args)
{
Int32 val1 = 10,val2 = 20;
bool status = true;

Console.WriteLine(val1 + val2);
Console.WriteLine(val1 < val2);
Console.WriteLine(!(status));
Console.ReadKey();
}
}
}

Code Explanation
1. Two Integer variables are defined, one being val1 and the other being val2. These will be used to showcase
relational and arithmetic operations. A Boolean variable is defined to showcase logical operations.
2. An example of the arithmetic operation is shown wherein the addition operator is carried out on val1 and val2.
The result is written to the console.
3. An example of the relational operation is shown wherein the less than operator is carried out on val1 and val2.
The result is written to the console.
4. An example of the logical operation is shown, wherein the logical operator (!) is applied to the status variable.
The logical NOT operator reverses the current value of any Boolean value. So if a Boolean value is ‘true’, the
logical NOT will return the value ‘false’ and vice versa. In our case since the value of the status variable is
‘true’, the result will show ‘false’. The result is written to the console.
OBJECT-BASED MANIPULATION

NET is object-oriented to the core. In fact, even ordinary variables are really full-
fledged objects in disguise. This means that common data types have the built-in smarts
to handle basic operations (such as counting the number of characters in a string). Even
better, it means you can manipulate strings, dates, and numbers in the same way in C#
and in VB. This wouldn't be true if developers used special keywords that were built
into the C# or VB language.
For example, every type in the .NET class library includes a ToString() method.

string myString;
int myInteger = 100;
// Convert a number to a string. myString will have the contents
"100".
myString = myInteger.ToString();

 C# | Type Casting
-Type conversion happens when we assign the value of one data type to another.
If the data types are compatible, then C# does Automatic Type Conversion. If not
comparable, then they need to be converted explicitly which is known as Explicit
Type conversion. For example, assigning an int value to a long variable.
It happens when:
-The two data types are compatible.
-When we assign value of a smaller data type to a bigger data type.
-For Example, in C#, the numeric data types are compatible with each other but
no automatic conversion is supported from numeric type to char or boolean. Also,
char and boolean are not compatible with each other.

Convert from Data Type Convert to Data Type

byte short, int, long, float, double

short int, long, float, double

int long, float, double

long float, double

float double
// C# program to demonstrate the
// Explicit Type Conversion

using System;
namespace Casting{

class GFG {

// Main Method
public static void Main(String []args)
{
double d = 765.12;

// Explicit Type Casting


int i = (int)d;

// Display Result
Console.WriteLine("Value of i is " +i);
}
}
}

Output:
Value of i is 765

C# provides built-in methods for Type-Conversions as follows :

Method Description
ToBoolean It will converts a type to Boolean value
ToChar It will converts a type to a character value
ToByte It will converts a value to Byte Value
ToDecimal It will converts a value to Decimal point value
ToDouble It will converts a type to double data type
ToInt16 It will converts a type to 16-bit integer
ToInt32 It will converts a type to 32 bit integer
ToInt64 It will converts a type to 64 bit integer
ToString It will converts a given type to string
ToUInt16 It will converts a type to unsigned 16 bit integer
ToUInt32 It will converts a type to unsigned 32 bit integer
ToUInt64 It will converts a type to unsigned 64 bit integer
// C# program to demonstrate the
// Built- In Type Conversion Methods
using System;
namespace Casting{

class GFG {

// Main Method
public static void Main(String []args)
{
int i = 12;
double d = 765.12;
float f = 56.123F;

// Using Built- In Type Conversion


// Methods & Displaying Result
Console.WriteLine(Convert.ToString(f));
Console.WriteLine(Convert.ToInt32(d));
Console.WriteLine(Convert.ToUInt32(f));
Console.WriteLine(Convert.ToDouble(i));
Console.WriteLine("bkbirla");
}
}
}

Output:
56.123
765
56
12
bkbirla

 Methods in System.String Class

 The String Type


-One of the best examples of how class members can replace built-in
functions is found with strings.
-In the past, every language has defined its own specialized functions
for string manipulation.
-In .NET, however, you use the methods of the String class, which
ensures consistency between all .NET languages.
-The following code snippet shows several ways to manipulate a
string by using its object nature:

Trim():
using System;
class HelloWorld {
static void Main() {
string myString=" this is my first code";
string myString1=" this is my first code ";
string myString2="this is my first code ";
Console.WriteLine(myString.Trim());
Console.WriteLine(myString1.Trim());
Console.WriteLine(myString2.Trim());
}
}

using System;
class HelloWorld {
static void Main() {
// Console.WriteLine("Hello World");
string myString="this is my first code";

Console.WriteLine(myString.Trim());
myString=myString.Substring(0,4);
Console.WriteLine(myString);
myString=myString.ToUpper();
Console.WriteLine(myString);
myString=myString.ToLower();
Console.WriteLine(myString);
myString=myString.Replace("is","at");
Console.WriteLine(myString);
int len=myString.Length;
Console.WriteLine(len);
}
}

-The first few statements use built-in methods, such as Trim(),


Substring(), ToUpper(), and Replace().
-These methods generate new strings, and each of these statements
replaces the current myString with the new string object.
-The final statement uses a built-in Length property, which returns an
integer that represents the number of characters in the string.
-Note that the Substring() method requires a starting offset and a
character length.
-Strings use zero-based counting. This means that the first letter is in
position 0, the second letter is in position 1, and so on.

Methods in System.String Class

-Length() Returns the number of characters in the string (as an integer).


-ToUpper() and ToLower()
Returns a copy of the string with all the characters changed to uppercase
or lowercase characters.
-Trim(), TrimEnd(), and TrimStart()
Removes spaces (or the characters you specify) from either end (or both
ends) of a string.
-PadLeft() and PadRight()
Adds the specified character to the appropriate side of a string as many
times as necessary to make the total length of the string equal to the
number you specify. For example, "Hi".PadLeft(5, '@') returns the string
@@@Hi.
using System;
class HelloWorld {
static void Main() {
string myString="World!";
Console.WriteLine(myString.PadRight(10,'*'));

}
}

OUTPUT:
World!****

using System;
class HelloWorld {
static void Main() {
// Console.WriteLine("Hello World");
string myString="World!";
Console.WriteLine(myString.PadLeft(10,'*'));

}
}
OUTPUT:
****World!

-Insert()
Puts another string inside a string at a specified (zero-based) index
position.
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello C#";
string s2 = s1.Insert(5,"-");
Console.WriteLine(s2);
}
}
OUTPUT: Hello- C#
-Remove()
Removes a specified number of characters from a specified position. For
example, Remove(0, 1) removes the first character.
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "RemoveMe";
Console.WriteLine(s1.Remove(0,5));
}
}

OUTPUT:
eMe

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "RemoveMe";
Console.WriteLine(s1.Remove(5));
}
}

OUTPUT:
Remov

-Replace()
Replaces a specified substring with another string. For example,
Replace("a", "b") changes all a characters in a string into b characters.
-Substring()
Extracts a portion of a string of the specified length at the specified
location (as a new string). For example, Substring(0, 2) retrieves the first
two characters.
-StartsWith() and EndsWith()
Determines whether a string starts or ends with a specified substring. For
example, StartsWith("pre") will return either true or false, depending on
whether the string begins with the letters pre in lowercase.

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str = "Icecream";


bool result;
result = str.StartsWith("Ice");
Console.WriteLine(result);
result = str.EndsWith("cream");
Console.WriteLine(result);
}
}
}
// Output:
True
True
Working with Date and Time in C#
C# includes DateTime struct to work with dates and times.

 To work with date and time in C#, create an object of the DateTime struct
using the new keyword. The following creates a DateTime object with the
default value.
 Example: Create DateTime Object
DateTime dt = new DateTime(); // assigns default value 01/01/0001
00:00:00
 Use different constructors of the DateTime struct to assign an initial value
to a DateTime object.

using System;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// 2015 is year, 12 is month, 25 is day
DateTime date1 = new DateTime(2015, 12, 25);
Console.WriteLine(date1); // 12/25/2015 12:00:00 AM

// 2015 - year, 12 - month, 25 – day, 10 – hour, 30 – minute, 50 - second


DateTime date2 = new DateTime(2012, 12, 25, 10, 30, 50);
Console.WriteLine(date2.ToString());// 12/25/2015 10:30:00 AM }
}
}
}

Output:
25-12-2015 00:00:00
25-12-2012 10:30:50

 Example: Invalid Date


DateTime dt = new DateTime(2015, 12, 32); //throws exception: day out of
range

Example2
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DateTime myDate = DateTime.Now;
Console.WriteLine(myDate);
myDate = myDate.AddDays(100);
Console.WriteLine(myDate);
string dateString = myDate.Month.ToString();
Console.WriteLine(dateString);

}
}
}

24-06-2024 14:52:29
02-10-2024 14:52:29
10

Example:

DateTime date1 = new DateTime(2023, 3, 11, 10, 30, 0);

This code creates a DateTime object representing March 11, 2023, 10:30 AM.

The DateTime class also provides various methods to format dates in different ways.
For example, the ToString method can format a DateTime object as a string. The
following code formats the date in the “dd MMM yyyy” format (e.g., “11 Mar 2023”)

string formattedDate = date1.ToString("dd MMM yyyy");

using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DateTime date1 = new DateTime(2023, 3, 11, 10, 30, 0);
string formattedDate = date1.ToString("dd MMM yyyy");
Console.WriteLine(formattedDate);

}
}
}

-For example, the following block of code creates a DateTime object,sets it to the
current date and time, and adds a number of days.
-It then creates a string that indicates the year that the new date falls in (for example,
2012).

using System;
namespace ConsoleApplication2
{

class Program
{
static void Main(string[] args)
{
DateTime myDate1 = DateTime.Now;
Console.WriteLine(myDate1);
DateTime myDate2 = DateTime.Now.AddHours(3000);
Console.WriteLine(myDate2);
TimeSpan difference;
difference = myDate2.Subtract(myDate1);
double numberOfMinutes;
numberOfMinutes = difference.TotalMinutes;
Console.WriteLine(numberOfMinutes);
}
}
}

The DateTime and TimeSpan Types

The DateTime and TimeSpan data types also have built-in methods and properties.
DateTime
The DateTime class is the most commonly used date class in C#. It represents a specific
date and time and has many properties and methods that allow you to perform
operations on it. DateTime objects can be created using various constructors, which
accept parameters such as year, month, day, hour, minute, second, and millisecond.

Example:

DateTime date1 = new DateTime(2023, 3, 11, 10, 30, 0);

This code creates a DateTime object representing March 11, 2023, 10:30 AM.

The DateTime class also provides various methods to format dates in different ways.
For example, the ToString method can format a DateTime object as a string. The
following code formats the date in the “dd MMM yyyy” format (e.g., “11 Mar 2023”)

string formattedDate = date1.ToString("dd MMM yyyy");

-For example, the following block of code creates a DateTime object,sets it to the
current date and time, and adds a number of days.
-It then creates a string that indicates the year that the new date falls in (for example,
2012).

DateTime myDate = DateTime.Now;


myDate = myDate.AddDays(100);
string dateString = myDate.Year.ToString();

-The next example shows how you can use a TimeSpan object to find
the total number of minutes between two DateTime objects:

DateTime myDate1 = DateTime.Now;


DateTime myDate2 = DateTime.Now.AddHours(3000);
TimeSpan difference;
difference = myDate2.Subtract(myDate1);
double numberOfMinutes;
numberOfMinutes = difference.TotalMinutes;

• The DateTime and TimeSpan classes also support the + and –


arithmetic operators, which do the same work as the built-in
methods. That means you can rewrite the example shown earlier like
this:

// Adding a TimeSpan to a DateTime creates a new DateTime.


DateTime myDate1 = DateTime.Now;
TimeSpan interval = TimeSpan.FromHours(3000);
DateTime myDate2 = myDate1 + interval;

// Subtracting one DateTime object from another produces a TimeSpan.


TimeSpan difference;
difference = myDate2 - myDate1;

Now : Gets the current date and time.


Today: Gets the current date and leaves time set to 00:00:00.

Year, Date, Month, Hour, Minute, Second, and Millisecond

Returns one part of the DateTime object as an integer. For example,


Month will return 12 for any day in December.

Add() and Subtract()


Adds or subtracts a TimeSpan from the DateTime. For convenience, these
operations are mapped to the + and – operators, so you can use them
instead when performing calculations with dates.

AddYears(), AddMonths(), AddDays(), AddHours(), AddMinutes(),


AddSeconds(), AddMilliseconds()
Adds an integer that represents a number of years, months, and so on, and
returns a new DateTime. You can use a negative integer to perform a date
subtraction.

IsLeapYear()
Returns true or false depending on whether the specified year is a leap
year.

using System;
public class IsLeapYear
{
public static void Main()
{
for (int year = 1994; year <= 2014; year++)
{
if (DateTime.IsLeapYear(year))
{
Console.WriteLine("{0} is a leap year.", year);

}
}
}
}
OUTPUT:

1996 is a leap year.


2000 is a leap year.
2004 is a leap year.
2008 is a leap year.
2012 is a leap year.

C# Math
The C# Math class has many methods that allows you to perform mathematical
tasks on numbers.

Math.Max(x,y)
The Math.Max(x,y) method can be used to find the highest value of x and y:

Math.Min(x,y)
The Math.Min(x,y) method can be used to find the lowest value of of x and y:

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Max(5, 10));
Console.WriteLine(Math.Min(5, 10));

}
}
}

Output:
10
5

Math.Sqrt(x)
The Math.Sqrt(x) method returns the square root of x:

using System;

namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Sqrt(64));
}
}
}
//8

Math.Abs(x)
The Math.Abs(x) method returns the absolute (positive) value of x:

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Abs(-4.7));
}
}
}
//4.7

Math.Round()
Math.Round() rounds a number to the nearest whole number:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Round(9.99));
Console.WriteLine(Math.Round(9.49));

}
}
}
//10
9

C# Conditions and If Statements

C# supports the usual logical conditions from mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

C# has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of C# code to be executed if a condition is True.

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 20;
int y = 18;
if (x > y)
{
Console.WriteLine("x is greater than y");
}
}
}
}

OUTPUT:
x is greater than y

The else Statement


Use the else statement to specify a block of code to be executed if the condition is False.

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int time = 20;
if (time < 18)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
}
}
}

OUTPUT:
Good evening.
The else if Statement
Use the else if statement to specify a new condition if the first condition is False.

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int time = 22;
if (time < 10)
{
Console.WriteLine("Good morning.");
}
else if (time < 20)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
}
}
}

OUTPUT:
Good evening.

C# Short Hand If...Else


Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary operator because it consists of
three operands. It can be used to replace multiple lines of code with a single line. It is often
used to replace simple if else statements:

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
Console.WriteLine(result);
}
}
}

OUTPUT:
Good evening.
C# Switch Statements
Use the switch statement to select one of many code blocks to be executed.

SyntaX
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}

This is how it works:

 The switch expression is evaluated once


 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed
 The break and default keywords will be described later in this chapter

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
}
}
}
}

OUTPUT:
Thursday

Loops

The while loop loops through a block of code as long as a specified condition is True:
SyntaX

while (condition)
{
// code block to be executed
}
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
}
}
}

OUTPUT:
0
1
2
3
4

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.

do {
// code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be executed at least once, even
if the condition is false, because the code block is executed before the condition is tested:

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 5);
}
}
}
OUTPUT:

0
1
2
3
4

C# For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:

for (statement 1; statement 2; statement 3)


{
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
}
}
}

OUTPUT:

0
1
2
3
4
The foreach Loop

 C# also provides a foreach loop that allows you to loop through the items in a set of data.
 With a foreach loop, you don’t need to create an explicit counter variable.
 Instead, you create a variable that represents the type of data for which you’re looking.
Your code will then loop until you’ve had a chance to process each piece of data in the set.
 The foreach loop is particularly useful for traversing the data in collections and arrays.
 For example, the next code segment loops through the items in an array by using foreach.

string[] stringArray = {"one", "two", "three"};


foreach (string element in stringArray)
{
// This code loops three times, with the element variable set to
// "one", then "two", and then "three".
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
// Declare an array
string[] cars;

// Add values, using new


cars = new string[] {"Volvo", "BMW", "Ford"};

foreach(string i in cars)
{
Console.WriteLine(i);
}

//Console.WriteLine(cars[0]);
}
}
}

OUTPUT:
Volvo
BMW
Ford
 This code has exactly the same effect as the example in the previous section, but it’s a little
simpler:
 In this case, the foreach loop examines each item in the array and tries to convert it to a
string. Thus, the foreach loop defines a string variable named element.
 If you used a different data type, you’d receive an error.
 The foreach loop has one key limitation: it’s read-only.
 For example, if you wanted to loop through an array and change the values in that array at
the same time, foreach code wouldn’t work.

Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
To declare an array, define the variable type with square brackets:
string[] cars;

We have now declared a variable that holds an array of strings.


To insert values to it, we can use an array literal - place the values in a comma-
separated list, inside curly braces:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:


int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You access an array element by referring to the index number. This statement accesses the
value of the first element in cars:

using System;

namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]);
}
}
}

OUTPUT:
Volvo
Change an Array Element
To change the value of a specific element, refer to the index number:

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
Console.WriteLine(cars[0]);
}
}
}
OUTPUT:
Opel

Array Length

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars.Length);
}
}
}

OUTPUT:
4

Other Ways to Create an Array


using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
// Declare an array
string[] cars;

// Add values, using new


cars = new string[] {"Volvo", "BMW", "Ford"};

// This would cause an error: cars = {"Volvo", "BMW", "Ford"};

Console.WriteLine(cars[0]);
}
}
}

OUTPUT:
Volvo

Methods
-A method is a block of code which only runs when it is called.

-You can pass data, known as parameters, into a method.

-Methods are used to perform certain actions, and they are also known as functions.

-Why use methods? To reuse code: define the code once, and use it many times.

Create a Method
A method is defined with the name of the method, followed by parentheses (). C#
provides some pre-defined methods, which you already are familiar with, such
as Main(), but you can also create your own methods to perform certain actions:
class Program{
static void MyMethod()
{ // code to be executed
}}
Example Explained
-MyMethod() is the name of the method
-static means that the method belongs to the Program class and not an object of the Program
class. You will learn more about objects and how to access methods through objects later in
this tutorial.
-void means that this method does not have a return value.

Call a Method
To call (execute) a method, write the method's name followed by two parentheses () and a
semicolon;
using System;
namespace MyApplication
{
class Program
{
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}

static void Main(string[] args)


{
MyMethod();
}
}
}

OUTPUT:
I just got executed!

using System;
namespace MyApplication
{
class Program
{
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}

static void Main(string[] args)


{
MyMethod();
MyMethod();
MyMethod();
}
}
}

OUTPUT:
I just got executed!
I just got executed!
I just got executed!

 DELEGATES :
 A delegate is a type that represents references to methods with a particular parameter list
and return type.
 When you instantiate a delegate, you can associate its instance with any method with a
compatible signature and return type. You can invoke (or call) the method through the
delegate instance.
 Delegates are used to pass methods as arguments to other methods.
 Delegates have the following properties:
 Delegates are similar to C++ function pointers, but delegates are fully object-oriented, and
unlike C++ pointers to member functions, delegates encapsulate both an object instance
and a method.
 Delegates allow methods to be passed as parameters.
 Delegates can be used to define callback methods.
 Delegates can be chained together; for example, multiple methods can be called on a
single event.

Example:
using System;
delegate void Calculator(int x,int y);
class Program
{
public static void Add(int a, int b)
{
Console.WriteLine(a+b);
}
public static void Sub(int a, int b)
{
Console.WriteLine(a - b);
}
public static void Mul(int a, int b)
{
Console.WriteLine(a * b);
}
static void Main(string[] args)
{
Calculator calc = new Calculator(Add);
calc(20, 30);
}
}

Output:
50

ReadLine() :
using System;
class abc{
public static void Main()
{
string name;
Console.WriteLine("Enter your name: ");
name = Console.ReadLine();
Console.WriteLine("Hello " + name + " Welcome!");
Console.ReadLine();
}
}

OUTPUT:
Enter your name:
vrinda
Hello vrinda Welcome!

Chapter 3
TYPES, OBJECTS, AND NAMESPACES

 THE BASICS ABOUT CLASSES


Class and Object are the basic concepts of Object-Oriented Programming which revolve around
the real-life entities. A class is a user-defined blueprint or prototype from which objects are
created. Basically, a class combines the fields and methods(member function which defines
actions) into a single unit. In C#, classes support polymorphism, inheritance and also provide
the concept of derived classes and base classes.

Declaring classes
Classes are declared by using the class keyword followed by a unique identifier, as shown in
the following example:
//[access modifier] - [class] - [identifier]
public class Customer
{
// Fields, properties, methods and events go here...
}

Creating objects
Although they're sometimes used interchangeably, a class and an object are different things. A
class defines a type of object, but it isn't an object itself. An object is a concrete entity based on
a class, and is sometimes referred to as an instance of a class.
Objects can be created by using the new keyword followed by the name of the class, like this:
Customer object1 = new Customer();
When an instance of a class is created, a reference to the object is passed back to the
programmer. In the previous example, object1 is a reference to an object that is based
on Customer. This reference refers to the new object but doesn't contain the object data itself.
In fact, you can create an object reference without creating an object at all:
Customer object2;
Constructors and initialization
created is called a constructor. The main use of constructors is to initialize private fields of the
class while creating an instance for the class. When you have not created a constructor in the
class, the compiler will automatically create a default constructor in the class. The default
constructor initializes all numeric fields in the class to zero and all string and object fields
to null.
Some of the key points regarding the Constructor are:
 A class can have any number of constructors.
 A constructor doesn&#39;t have any return type, not even void.
 A static constructor can not be a parametrized constructor.
 Within a class you can create only one static constructor.
Constructors can be divided into 5 types:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor
1. Default Constructor
A constructor without any parameters is called a default constructor; in other words this type of
constructor does not take parameters. The drawback of a default constructor is that every
instance of the class will be initialized to the same values and it is not possible to initialize each
instance of the class to different values.
The default constructor initializes:
1. All numeric fields in the class to zero.
2. All string and object fields to null.
Example
using System;
namespace DefaultConstructor {
class addition
{
int a, b;
public addition() //default Constructor
{
a = 100;
b = 175;
}
public static void Main()
{
addition obj = new addition(); //an object is created , constructor is called
Console.WriteLine(obj.a);
Console.WriteLine(obj.b);
Console.Read();
}
}
}

OUTPUT
100
175

2.Parameterized Constructor
A constructor with at least one parameter is called a parameterized constructor. The
advantage of a parameterized constructor is that you can initialize each instance of the class to
different values.

using System;
namespace Constructor
{
class ParaConstructor
{
public int a, b;
public ParaConstructor(int x, int y)
{
a = x;
b = y;
}
}
class MainClass
{
static void Main()
{
paraconstrctor v = new paraconstrctor(100, 175);
Console.WriteLine(“\t”);
Console.WriteLine(“value of a=” + v.a );
Console.WriteLine(“value of b=”+ v.b);
Console.Read();
}
}
}

OUTPUT
Value of a=100
Value of b=175

3.Copy Constructor
The constructor which creates an object by copying variables from another object is called a
copy constructor. The purpose of a copy constructor is to initialize a new instance to the values
of an existing instance.
The copy constructor is invoked by instantiating an object of type employee and passing it the
object to be copied.
Example

employee emp1=new employee (emp2);

//Now, emp1 is a copy of emp2.

using System;
namespace ConsoleApplication6
{
class employee
{
private string name;
private int age;
public employee(string name, int age) // Instance constructor
{
this.name = name;
this.age = age;
}
public employee(employee emp) // declaring Copy constructor.
{
name = emp.name;
age = emp.age;
}

public string Details // Get deatils of employee


{
get //get property used to return the value
{
return "The age of " + name + " is " + age.ToString();
}
}
}
class empdetail
{

static void Main()


{
employee emp1 = new employee("Vithal", 23); // Create a new employee object.
employee emp2 = new employee(emp1); // here is emp1 details is copied to
emp2.
//Console.WriteLine(emp1.Details); // data from one constructor get copied into copy
constructor
Console.WriteLine(emp2.Details);
Console.ReadLine();
}
}

OUTPUT
The age of Vithal is 23

4.Static Constructor
When a constructor is created as static, it will be invoked only once for all of instances of the
class and it is invoked during the creation of the first instance of the class or the first reference
to
a static member in the class. A static constructor is used to initialize static fields of the class
and to write the code that needs to be executed only once.

Some key points of a static constructor is:


1. A static constructor does not take access modifiers or have parameters.
2. A static constructor is called automatically to initialize the class before the first instance
is created or any static members are referenced.
3. A static constructor cannot be called directly.
4. The user has no control on when the static constructor is executed in the program.
5. A typical use of static constructors is when the class is using a log file and the constructor
is used to write entries to this file.

using System;
namespace Constructor
{
public class employee
{
static employee() // Static constructor declaration
{
Console.WriteLine("The static constructor");
}
public static void Salary()
{
Console.WriteLine();
Console.WriteLine("The Salary method");
}
}
class details
{
static void Main()
{
Console.WriteLine("----------Static constructor example------------------");
Console.WriteLine();
employee.Salary();
Console.ReadLine();
}}}
OUTPUT
----------Static constrctor example------------------
The static constructor
The Salary method
5.Private Constructor
When a constructor is created with a private specifier, it is not possible for other classes to
derive from this class, neither is it possible to create an instance of this class. They are usually
used in classes that contain static members only.
Some key points of a private constructor are:
1. One use of a private constructor is when we have only static members.
2. It provides an implementation of a singleton class pattern
3. Once we provide a constructor that is either private or public or any, the compiler will not
add the parameter-less public constructor to the class.

using System;
namespace defaultConstructor
{
public class Counter
{
private Counter() //private constructor declaration
{
}
public static int currentview;
public static int visitedCount()
{
return ++ currentview;
}
}
class viewCountedetails
{
static void Main()
{
// Counter aCounter = new Counter(); // Error
Console.WriteLine(“-------Private constructor example ---------“);
Console.WriteLine();
Counter.currentview = 500;
Counter.visitedCount();
Console.WriteLine(“Now the view count is: {0}”, Counter.currentview);
Console.ReadLine();
}
}
}

OUTPUT
-------Private constructor example----------
Now the view count is: 501
Example 2:
using System;
namespace ConsoleApplication5
{
using System;
class abc
{
// Static variable
static int s;

// Non-static variable
int ns;

// Declaration of
// static constructor
static abc()
{
Console.WriteLine("It is static constructor");
}

// Declaration of
// non-static constructor
public abc()
{
Console.WriteLine("It is non-static constructor");
}
// Main Method
static void Main(string[] args)
{
abc obj1 = new abc();
}
}

OUTPUT:
It is static constructor
It is non-static constructor
Destructors
 Destructors in C# are methods inside the class used to destroy
instances of that class when they are no longer needed.
 In C#, destructor (finalizer) is used to destroy objects of class when
the scope of an object ends.
 The Destructor is called implicitly by the .NET Framework’s Garbage
collector and therefore programmer has no control as when to invoke
the destructor.
 It has the same name as the class and starts with a tilde ~ For
example,
class Test {
...
//destructor
~Test() {
...
}
}
 Here, ~Test() is the destructor.

using System;
namespace CsharpDestructor
{
class Person
{
public Person()
{
Console.WriteLine("Constructor called.");
}
// destructor
~Person()
{
Console.WriteLine("Destructor called.");
}
public static void Main(string[] args)
{
//creates object of Person
Person p1 = new Person();
}
}
}
Example :
using System;
namespace ConsoleApplication5
{ class Person
{
string name;
void getName()
{
Console.WriteLine("Name: " + name);
}
// destructor
~Person()
{
Console.WriteLine("Destructor called.");
}
public static void Main(string[] args)
{ // creates object of Person
Person p1 = new Person();
p1.name = "Ed Sheeran";
p1.getName();
}
}
}

Features of Destructors
There are some important features of the C# destructor. They are as
follows:
 We can only have one destructor in a class.
 A destructor cannot have access modifiers, parameters, or return
types.
 A destructor is called implicitly by the Garbage collector of the .NET
Framework.
 It cannot be overloaded or inherited.

this Object in C#
 The “this” keyword in C# is used to refer to the current instance of the class.
 It is also used to differentiate between the method parameters and class fields if
they both have the same name.
 Another usage of “this” keyword is to call another constructor from a constructor
in the same class.
 Here, for an example, we are showing a record of Students i.e: id, Name, Age,
and Subject.
 To refer to the fields of the current class, we have used the “this” keyword in C#.

using System;
namespace ConsoleApplication5
{ class Geeks
{
// instance member
public string Name;
public string GetName()
{
return Name;
}
public void SetName(string Name)
{
// referring to current instance
//"this.Name" refers to class member
this.Name = Name;
}
}
class program
{
// Main Method
public static void Main()
{
Geeks obj = new Geeks();
obj.SetName("Geeksforgeeks");
Console.WriteLine(obj.GetName());
}
}
}

Value Type and Reference Type


In C#, these data types are categorized based on how they store their
value in the memory. C# includes the following categories of data types:
1. Value type
2. Reference type

1. Value type
A data type is a value type if it holds a data value within its own memory space.
It means the variables of these data types directly contain values.
For example, consider integer variable int i = 100;

using System;
namespace ConsoleApplication9
{
class Program
{
static void ChangeValue(int x)
{
x = 200;
Console.WriteLine(x);
}
static void Main(string[] args)
{
int i = 100;
Console.WriteLine(i);
ChangeValue(i);
Console.WriteLine(i);
}
}
}

Cached Result
100
200
100

Reference Type
Unlike value types, a reference type doesn't store its value directly. Instead, it
stores the address where the value is being stored. In other words, a reference
type contains a pointer to another memory location that holds the data.
For example, consider the following string variable:
string s = "Hello World!!";

Understanding Namespaces
 Namespaces are used to organize the classes.
 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 System.Console where System is the namespace
and Console is the class. To access the class of a namespace, we need to use
namespacename.classname. We can use using keyword so that we don't have to
use complete name all the time.
 In C#, global namespace is the root namespace. The global::System will always
refer to the namespace "System" of .Net Framework.

using System;
namespace abc
{
public class Hello
{
public void sayHello() { Console.WriteLine("Hello First Namespace"); }
}
}
namespace Second
{
public class Hello
{
public void sayHello() { Console.WriteLine("Hello Second Namespace"); }
}
}
public class TestNamespace
{
public static void Main()
{
abc.Hello h1 = new abc.Hello();
Second.Hello h2 = new Second.Hello();
h1.sayHello();
h2.sayHello();
}
}
Output:
Hello First Namespace
Hello Second Namespace

Assemblies in C#
 An assembly is a collection of types and resources that are built to work together
and form a logical unit of functionality.
 Assemblies take the form of executable (.exe) or dynamic link library (. dll) files,
and are the building blocks of .NET applications.
 An Assembly is a basic building block of .Net Framework applications. It is
basically a compiled code that can be executed by the CLR.
 An assembly is a collection of types and resources that are built to work together
and form a logical unit of functionality. An Assembly can be a DLL or exe
depending upon the project that we choose.
 Assemblies are basically the following two types:
1. Private Assembly
2. Shared Assembly

1. Private Assembly
 It is an assembly that is being used by a single application only.
 Suppose we have a project in which we refer to a DLL so when we build that
project that DLL will be copied to the bin folder of our project.
 That DLL becomes a private assembly within our project. Generally, the DLLs that
are meant for a specific project are private assemblies.

2. Shared Assembly
 Assemblies that can be used in more than one project are known to be a shared
assembly.
 Shared assemblies are generally installed in the GAC.
 Assemblies that are installed in the GAC are made available to all the .Net
applications on that machine.
Global Assembly
 CacheEach computer where the Common Language Runtime is installed has a
machine-wide code cache called the Global Assembly Cache.
 The Global Assembly Cache stores assemblies specifically designated to be
shared by several applications on the computer .
ADVANCED CLASS PROGRAMMING
 Part of the art of object-oriented programming is determining object relations.
Inheritance in C#
OOPs support the six different types of inheritance as given below :
1. Single inheritance
2. Multi-level inheritance
3. Multiple inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

 In C#, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically.
 In such way, you can reuse, extend or modify the attributes and behaviors which
is defined in other class.
 In C#, the class which inherits the members of another class is called derived
class and the class whose members are inherited is called base class.
 The derived class is the specialized class for the base class.
 Advantage of C# Inheritance: Code reusability: Now you can reuse the
members of your parent class. So, there is no need to define the member again.
So less code is required in the class.

1. Single Level Inheritance Example


When one class inherits another class, it is known as single level inheritance.
Let's see the example of single level inheritance which inherits the fields only.

1. using System;
2. public class Employee
3. {
4. public float salary = 40000;
5. }
6. public class Programmer: Employee
7. {
8. public float bonus = 10000;
9. }
10. class TestInheritance{
11. public static void Main(string[] args)
12. {
13. Programmer p1 = new Programmer();
14.
15. Console.WriteLine("Salary: " + p1.salary);
16. Console.WriteLine("Bonus: " + p1.bonus);
17.
18. }
19. }

Output:
Salary: 40000
Bonus: 10000

C# Single Level Inheritance Example: Inheriting Methods


Let's see another example of inheritance in C# which inherits methods only.
1. using System;
2. public class Animal
3. {
4. public void eat() { Console.WriteLine("Eating..."); }
5. }
6. public class Dog: Animal
7. {
8. public void bark() { Console.WriteLine("Barking..."); }
9. }
10. class TestInheritance2{
11. public static void Main(string[] args)
12. {
13. Dog d1 = new Dog();
14. d1.eat();
15. d1.bark();
16. }
17. }

Output:
Eating...
Barking...

2. Multi Level Inheritance


 When one class inherits another class which is further inherited by another class,
it is known as multi level inheritance in C#.
 Inheritance is transitive so the last derived class acquires all the members of all
its base classes.

1. using System;
2. public class Animal
3. {
4. public void eat() { Console.WriteLine("Eating..."); }
5. }
6. public class Dog: Animal
7. {
8. public void bark() { Console.WriteLine("Barking..."); }
9. }
10. public class BabyDog : Dog
11. {
12. public void weep() { Console.WriteLine("Weeping..."); }
13. }
14. class TestInheritance2{
15. public static void Main(string[] args)
16. {
17. BabyDog d1 = new BabyDog();
18. d1.eat();
19. d1.bark();
20. d1.weep();
21. }
22. }

Output:
Eating...
Barking...
Weeping...

3. Multiple inheritance :
 In this inheritance, a derived class is created from more than one base class. This
inheritance is not supported by .NET Languages like C#, F# etc. and Java
Language.
 In the given example, class c inherits the properties and behavior of class B and
class A at same level. So, here A and Class B both are the parent classes for Class
C.
using System;
namespace ConsoleApplication6
{
public class Father
{
public string FatherName()
{
return "Ravi";
}
}
// Derived Class
public class ChildFirst : Father
{
public string ChildDName()
{
return "Rohan";
}
}

// Derived Class
public class ChildSecond : Father
{
public string ChildDName()
{
return "Nikhil";
}
}

class GFG
{

static public void Main()


{
ChildFirst first = new ChildFirst();

// Displaying Child Name and Father Name for


// ChildFirst
Console.WriteLine("My name is " + first.ChildDName() +
". My father name is " +
first.FatherName() + ".");
ChildSecond second = new ChildSecond();

// Displaying Child Name and Father Name for


// ChildSecond
Console.WriteLine("My name is " + second.ChildDName() +
". My father name is " +
second.FatherName() + ".");
}

Output:
My name is Rohan. My father name is Ravi.
My name is Nikhil. My father name is Ravi.

4. Hybrid inheritance :
This is combination of more than one inheritance. Hence, it may be a combination of
Multilevel and Multiple inheritance or Hierarchical etc.
using System;
namespace Inheritance {

// base class
class Animal {

public string name;

public void display() {


Console.WriteLine("I am an animal");
}

// derived class of Animal


class Dog : Animal {

public void getName() {


Console.WriteLine("My name is " + name);
}
}

class Program {

static void Main(string[] args) {

// object of derived class


Dog labrador = new Dog();

// access field and method of base class


labrador.name = "Rohu";
labrador.display();

// access method from own class


labrador.getName();

Console.ReadLine();
}

}
}

Output

I am an animal
My name is Rohu

Interfaces in C#
 Interface is like a contract. In the human world, the contract between the two or
more humans binds them to act as per the contract.
 In the same way, the interface includes the declaration of one or more
functionalities.
 Entities that implement the interface must define functionalities declared in the
interface. In C#, a class or a struct can implement one or more interfaces
 In C# an interface can be defined using the interface keyword.
 Interfaces can contain methods, properties, indexers, and events as members.
 You cannot use any access modifier for any member of an interface. All the
members by default are public members

using System;
namespace MyApplication
{
// Interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}

// Pig "implements" the IAnimal interface


class Pig : IAnimal
{
public void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}

class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}
}

Output:
The pig says: wee wee

You might also like