AWP Unit 1
AWP Unit 1
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.
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
• 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);
• 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
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
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
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);
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:
+ Addition 1+1=2
– Subtraction 5–2=3
* Multiplcation 2 * 5 = 10
% 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.
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;
// Display Result
Console.WriteLine("Value of i is " +i);
}
}
}
Output:
Value of i is 765
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;
Output:
56.123
765
56
12
bkbirla
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);
}
}
}
}
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) {
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
Output:
25-12-2015 00:00:00
25-12-2012 10:30:50
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:
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”)
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 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:
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”)
-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).
-The next example shows how you can use a TimeSpan object to find
the total number of minutes between two DateTime objects:
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:
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
You can use these conditions to perform different actions for different decisions.
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
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.
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;
}
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
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:
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
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.
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;
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
Console.WriteLine(cars[0]);
}
}
}
OUTPUT:
Volvo
Methods
-A method is a block of code which only runs when it is called.
-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!");
}
OUTPUT:
I just got executed!
using System;
namespace MyApplication
{
class Program
{
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}
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
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'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
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;
}
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.
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());
}
}
}
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. 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
Output:
Eating...
Barking...
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
{
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 {
class Program {
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)
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}
}
Output:
The pig says: wee wee