Unit 3 Course
Unit 3 Course
In the Create a new project window, select All languages, and then choose C#
from the dropdown list. Choose Windows from the All platforms list, and choose
Console from the All project types list.
After you apply the language, platform, and project type filters, choose the
Console App template, and then select Next.
There are two methods for writing to the console window, which are used
extensivly,
Console.Write()
Console.WriteLine()
Console.WriteLine()
This is one of the output methods for console-class in the runtime library. This
does the same but adds a newline character at the end of the output using
specified format information. WriteLine() method has 18 overloads as shown
below.
Console.ReadLine():
This method reads a string text from the console window. This will read input
text from the user at the console windows and display the string at console
windows when the user presses the enter key.
Switch:
Switch is a selection statement that chooses a single section to execute from a list
of candidates based on a pattern match with the match expression.
abstract base as
Classes in C#
A class is like a blueprint of a specific object that has certain attributes and
features. For example, a car should have some attributes such as four wheels,
two or more doors, steering, a windshield, etc. It should also have some
functionalities like start, stop, run, move, etc. Now, any object that has these
attributes and functionalities is a car. Here, the car is a class that defines some
specific attributes and functionalities. Each individual car is an object of the car
class. You can say that the car you are having is an object of the car class.
Define a Class:
In C#, a class can be defined by using the class keyword. Let's define a class
named 'Student'.
class Student
{
Field
A class can have one or more fields. It is a class-level variable that holds a
value. Generally, field members should have a private access modifier used
with property.
Example: Field
class Student
{
public int id;
Property
A property encapsulates a private field using setter and getter to assign and
retrieve underlying field value.
Example: Property
class Student
{
private int id;
In C#, an object of a class can be created using the new keyword and assign
that object to a variable of a class type. For example, the following creates
an object of the Student class and assign it to a variable of the Student
type.
mystudent.GetFullName();
You can create multiple objects of a class with different values of properties and
fields.
Example: Create Multiple Objects of a Class
Student mystudent1 = new Student();
mystudent1.FirstName = "Steve";
mystudent1.LastName = "Jobs";
Namespaces play an important role in managing related classes in C#. The .NET
Framework uses namespaces to organize its built-in classes. For example,
there are some built-in namespaces in .NET such as System, System.Linq,
System.Web, etc. Each namespace contains related classes.
Example: Namespace
namespace School
{
// define classes here
}
The following namespace contains the Student and Course classes.
Example: Namespace
namespace School
{
class Student
{
class Course
{
}
}
Variables in C#
Variables in C# are the same as variables in mathematics. Before we
understand what is a variable, let's understand the expressions. The followings
are examples of expressions.
Example: Expressions
10 + 20
5*2
10/2
The result of the above expressions are fixed e.g. 10 + 20 = 30, 5 * 2 = 10 and
10/2 = 5. Now, consider the following expressions.
1. var varInt = 1;
2. var varChar = 'a';
3. var varString = "abcdef";
Numbers:
Integer Types:
Byte:
The byte data type stores numbers from 0 to 255. It occupies 8-bit in the
memory. The byte keyword is an alias of the Byte struct in .NET.
sbyte sb2 = 127;
Short:
The short data type is a signed integer that can store numbers from -32,768
to 32,767. It occupies 16-bit memory. The short keyword is an alias for
Int16 struct in .NET.
short s = -31768;
Int:
The int data type is 32-bit signed integer. It can store numbers from -
2,147,483,648 to 2,147,483,647. The int keyword is an alias of Int32 struct
in .NET.
int i = -2047483648;
Long:
The long type is 64-bit signed integers. It can store numbers from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use l or L suffix
with number to assign it to long type variable. The long keyword is an alias
of Int64 struct in .NET.
long l1 = -9123372036854775808;
Float:
The float data type can store fractional numbers from 3.4e−038 to
3.4e+038. It occupies 4 bytes in the memory. The float keyword is an alias
of Single struct in .NET.
Use f or F suffix with literal to make it float type.
float f1 = 123456.5F;
Double:
The double data type can store fractional numbers from 1.7e−308 to
1.7e+308. It occupies 8 bytes in the memory. The double keyword is an
alias of the Double struct in .NET.
Use d or D suffix with literal to make it double type.
double d1 = 12345678912345.5d;
Decimal:
The decimal data type can store fractional numbers from ±1.0 x 10-28 to
±7.9228 x 1028. It occupies 16 bytes in the memory. The decimal is a
keyword alias of the Decimal struct in .NET.
The decimal type has more precision and a smaller range than both float
and double, and so it is appropriate for financial and monetary calculations.
Use m or M suffix with literal to make it decimal type.
decimal d1 = 123456789123456789123456789.5m;
Strings in C#:
Strings are used for storing text.
A string variable contains a collection of characters surrounded by double
quotes:
string s = "Hii";
String Length:
A string in C# is actually an object, which contain properties and methods
that can perform certain operations on strings. For example, the length of a
string can be found with the Length property:
Other Methods:
There are many string methods available, for example ToUpper() and
ToLower(), which returns a copy of the string converted to uppercase or
lowercase.
string txt = "Hello World";
Console.WriteLine(txt.ToUpper()); // Outputs "HELLO WORLD"
Console.WriteLine(txt.ToLower()); // Outputs "hello world"
Console.WriteLine(newDate);//1/1/2016 1:20:55 AM
}
public class TestStructs
{
public static void Main()
{
Output:
Area of Rectangle is: 20
height = h;
}
public void areaOfRectangle() {
Console.WriteLine("Area of Rectangle is: "+(width*height)); }
}
Output:
Area of Rectangle is: 30
.
.
}
enum Level
{
Low,
Medium,
High
}
class Program
{
static void Main(string[] args)
{
Output:
Medium
enum Months
{
January, // 0
February, // 1
March, // 2
April, // 3
May, // 4
June, // 5
July // 6
Console.WriteLine(myNum);
}
Output:
April
The StringBuilder performs faster than the string if you modify a string value
multiple times. If you modify a string value more than five times then you
should consider using the StringBuilder than a string.
Operators in C#:
Addition: The ‘+’ operator adds two operands. For example, x+y.
Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
Division: The ‘/’ operator divides the first operand by the second. For
example, x/y.
Modulus: The ‘%’ operator returns the remainder when first operand is
divided by the second. For example, x%y.
using System;
namespace Arithmetic
{
class GFG
{
// Main Function
static void Main(string[] args)
{
int result;
int x = 10, y = 5;
// Addition
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
// Subtraction
result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);
// Multiplication
result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result);
// Division
result = (x / y);
Console.WriteLine("Division Operator: " + result);
// Modulo
result = (x % y);
Console.WriteLine("Modulo Operator: " + result);
}
}
}
Output:
Addition Operator: 15
Subtraction Operator: 5
Multiplication Operator: 50
Division Operator: 2
Modulo Operator: 0
Relational Operators:
Relational operators are used for comparison of two values. Let’s see them
one by one:
‘=='(Equal To) operator checks whether the two given operands are equal
or not. If so, it returns true. Otherwise it returns false. For example, 5==5
will return true.
‘!='(Not Equal To) operator checks whether the two given operands are
equal or not. If not, it returns true. Otherwise it returns false. It is the exact
boolean complement of the ‘==’ operator. For example, 5!=5 will return
false.
‘>'(Greater Than) operator checks whether the first operand is greater than
the second operand. If so, it returns true. Otherwise it returns false. For
example, 6>5 will return true.
‘<‘(Less Than) operator checks whether the first operand is lesser than the
second operand. If so, it returns true. Otherwise it returns false. For
example, 6<5 will return false.
‘>='(Greater Than Equal To) operator checks whether the first operand is
greater than or equal to the second operand. If so, it returns true.
Otherwise it returns false. For example, 5>=5 will return true.
‘<='(Less Than Equal To) operator checks whether the first operand is lesser
than or equal to the second operand. If so, it returns true. Otherwise it
returns false. For example, 5<=5 will also return true.
using System;
namespace Relational {
class GFG {
// Main Function
static void Main(string[] args)
{
bool result;
int x = 5, y = 10;
// Equal to Operator
result = (x == y);
}
}
Output:
Equal to Operator: False
Logical Operators:
class GFG {
// Main Function
static void Main(string[] args)
{
bool a = true,b = false, result;
// AND operator
result = a && b;
Console.WriteLine("AND Operator: " + result);
// OR operator
result = a || b;
Console.WriteLine("OR Operator: " + result);
// NOT operator
result = !a;
Console.WriteLine("NOT Operator: " + result);
}
}
}
Output:
AND Operator: False
OR Operator: True
NOT Operator: False
Bitwise Operators:
In C#, there are 6 bitwise operators which work at bit level or used to
perform bit by bit operations. Following are the bitwise operators :
& (bitwise AND) Takes two numbers as operands and does AND on every
bit of two numbers. The result of AND is 1 only if both bits are 1.
| (bitwise OR) Takes two numbers as operands and does OR on every bit of
two numbers. The result of OR is 1 any of the two bits is 1.
^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit
of two numbers. The result of XOR is 1 if the two bits are different.
<< (left shift) Takes two numbers, left shifts the bits of the first operand,
the second operand decides the number of places to shift.
>> (right shift) Takes two numbers, right shifts the bits of the first operand,
the second operand decides the number of places to shift.
Example:
// C# program to demonstrate the working
// of Bitwise Operators
using System;
namespace Bitwise {
class GFG {
// Main Function
static void Main(string[] args)
{
int x = 5, y = 10, result;
// Bitwise OR Operator
result = x | y;
Console.WriteLine("Bitwise OR: " + result);
}
}
}
Output:
Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -6
Bitwise Left Shift: 20
Bitwise Right Shift: 1
Assignment Operators:
Example:
a = 10;
b = 20;
ch = 'y';
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
Example:
(a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
Example:
(a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.
(a %= b) can be written as (a = a % b)
If initially value stored in a is 6. Then (a %= 2) = 0.
Important points:
When you want to chop the functionality of the class, method, interface, or
structure into multiple files, then you should use partial keyword and all the
files are mandatory to be available at compile time for creating the final file.
The partial modifier can only present instantly before the keywords like struct,
class, and interface.
Every part of the partial class definition should be in the same assembly and
namespace, but you can use a different source file name.
Every part of the partial class definition should have the same accessibility as
private, protected, etc.
If any part of the partial class is declared as an abstract, sealed, or base, then
the whole class is declared of the same type.
The user is also allowed to use nested partial types.
Dissimilar parts may have dissimilar base types, but the final type must inherit
all the base types.
Consider the following EmployeeProps.cs and EmployeeMethods.cs files that
contain the Employee class.
EmployeeProps.cs:
public partial class Employee
{
public int EmpId { get; set; }
public string Name { get; set; }
}
EmployeeMethods.cs:
public partial class Employee
{
//constructor
public Employee(int id, string name){
this.EmpId = id;
this.Name = name;
}
public void DisplayEmpInfo() {
Console.WriteLine(this.EmpId + " " this.Name);
}
}
Syntax:
Static Methods:
Syntax:
static class Class_name {
}
}
Difference between static and non-static class:
Static class is defined using static Non-Static class is not defined by using
keyword. static keyword.
In static class, you are not allowed to In non-static class, you are allowed to
create objects. create objects using new keyword.
The data members of static class can The data members of non-static class
be directly accessed by its class is not directly accessed by its class
name. name.
Static class always contains static Non-static class may contain both
members. static and non-static methods.
Static class cannot inherit from Non-static class can be inherited from
another class. another class.
class Obj {
class obj1 {
// Main method
static public void Main()
{
Output:
Author Name: Ankita Saini
Author Id: 102
Total no of articles: 178
{
}
public class Big: Small
{
}
As per the above example classes, small is a base class for big and big is a
base class for bigger. The point to remember here is that a derived class will
always have something more than a base class, so the base class is
relatively smaller than the derived class.
Extension methods in C#:
Extension methods, as the name suggests, are additional methods. Extension
methods allow you to inject additional methods without modifying, deriving or
recompiling the original class, struct or interface. Extension methods can be
added to your own custom class, .NET framework classes, or third party classes
or interfaces.
In the following example, IsGreaterThan() is an extension method for int type,
which returns true if the value of the int variable is greater than the supplied
integer parameter.
Example: Extension Method
int i = 10;
The IsGreaterThan() method is not a method of int data type (Int32 struct). It is
an extension method written by the programmer for the int data type. The
IsGreaterThan() extension method will be available throughout the application
by including the namespace in which it has been defined.
{
public static class IntExtensions
{
public static bool IsGreaterThan(this int i, int value)
{
class Program
{
static void Main(string[] args)
{
int i = 10;
Console.WriteLine(result);
}
}
Output:
False
Exception Handling:
Here, you will learn about exception handling in C# using try, catch, and finally
blocks.
Exceptions in the application must be handled to prevent crashing of the
program and unexpected result, log exceptions and continue with other
functionalities. C# provides built-in support to handle the exception using try,
catch & finally blocks.
Syntax:
try
{
// put the code here that may raise exceptions
}
catch
{
// handle exception here
}
finally
{
// final cleanup code
}
try block: Any suspected code that may raise exceptions should be put
inside a try{ } block. During the execution, if an exception occurs, the
flow of the control jumps to the first matching catch block.
catch block: The catch block is an exception handler block where you
can perform some action such as logging and auditing an exception. The
catch block takes a parameter of an exception type using which you can
get the details of an exception.
{
Console.Write("Error occurred.");
}
finally
{
A try block must be followed by catch or finally or both blocks. The try
block without a catch or finally block will give a compile-time error.
{
Console.WriteLine("Enter a number: ");
var num = int.parse(Console.ReadLine());
}
finally
{
Console.Write("Re-try with a different number.");
}
}
}
C# Conditions & Loops:
Syntax:
if(condition)
{
// code if condition is true
}
else
{
// code if condition is false
}
using System;
class Program{
// If-else statement
if (x == y)
{
Output:
Both strings are not equal..!!
using System;
class Program{
int y = 100;
// If-else statement
if (x >= y)
{
// else statement
else
{
Console.WriteLine("x is not greater than y");
}
}
}
Output:
x is not greater than y
Ternary Operator ?:
C# includes a decision-making operator ?: which is called the conditional
operator or ternary operator. It is the short form of the if else conditions.
Syntax:
var result = x > y ? "x is greater than y" : "x is less than y";
Console.WriteLine(result);
output:
x is greater than y
Console.WriteLine(result);
Switch Statement:
In C#, Switch statement is a multiway branch statement. It provides an
efficient way to transfer the execution to different parts of a code based
on the value of the expression. The switch expression is of integer type
such as int, char, byte, or short, or of an enumeration type, or of string
type. The expression is checked for different cases and the one match is
executed.
Syntax:
switch (expression) {
.
case valueN: // statement sequence
break;
}
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.
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" (day 4)
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.
Syntax:
{
//code block
}
While Loop:
Looping in a programming language is a way to execute a statement or a
set of statements multiple number of times depending on the result of the
condition to be evaluated. while loop is an Entry Controlled Loop in C#.
The test condition is given in the beginning of the loop and all statements
are executed till the given boolean condition satisfies, when the condition
becomes false, the control will be out from the while loop.
Syntax:
The while loop starts with the while keyword, and it must include a boolean
conditional expression inside brackets that returns either true or false. It
executes the code block until the specified conditional expression returns
false.
Example:
int i = 0; // initialization
while (i < 10) // condition
{
Console.WriteLine("i = {0}", i);
i++; // increment
}
Output:
i=0
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
Above, a while loop includes an expression i < 10. Inside a while loop, the
value of i increased to 1 using i++. The above while loop will be executed
when the value of i equals to 10 and a condition i < 10 returns false.
while (i < 2)
{
Console.WriteLine("i = {0}", i);
i++;
while (j < 2)
{
Console.WriteLine("j = {0}", j);
j++;
}
Output:
i=0
j=1
i=1
do while Loop:
The do while loop is the same as while loop except that it executes the
code block at least once.
Syntax:
do
{
//code block
} while(condition);
Example:
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
Output:
0
1
2
3
4
C# Collections:
Array:
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;
Example:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]);
// Outputs Volvo
Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
Multidimensional Array:
However, if you want to store data as a tabular form, like a table with rows
and columns, you need to get familiar with multidimensional arrays.
Arrays can have any number of dimensions. The most common are two-
dimensional arrays (2D).
Two-Dimensional Arrays:
To create a 2D array, add each array within its own set of curly braces, and
insert a comma (,) inside the square brackets:
Example:
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
This statement accesses the value of the element in the first row (0) and
third column (2) of the numbers array:
Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
ArrayList:
ArrayList represents an ordered collection of an object that can be indexed
individually. It is basically an alternative to an array. It also allows dynamic
memory allocation, adding, searching and sorting items in the list.
Characteristics:
It is different from the arrays. A List<T> can be resized dynamically but
arrays cannot.
List<T> class can accept null as a valid value for reference types and it also
allows duplicate elements.
If the Count becomes equals to Capacity, then the capacity of the List
increased automatically by reallocating the internal array. The existing
elements will be copied to the new array before the addition of the new
element.
List<T> class is the generic equivalent of ArrayList class by implementing
the IList<T> generic interface.
This class can use both equality and ordering comparer.
List<T> class is not sorted by default and elements are accessed by zero-
based index.
For very large List<T> objects, you can increase the maximum capacity to 2
billion elements on a 64-bit system by setting the enabled attribute of the
configuration element to true in the run-time environment.
List<int> primeNumbers = new List<int>();
primeNumbers.Add(1); // adding elements using add() method
primeNumbers.Add(3);
primeNumbers.Add(5);
primeNumbers.Add(7);
Declaration of Delegates:
Delegate type can be declared using the delegate keyword. Once a delegate
is declared, delegate instance will refer and call those methods whose
return type and parameter-list matches with the delegate declaration.
Syntax:
[modifier] delegate [return_type] [delegate_name] ([parameter_list]);
• Func Delegate:
C# includes built-in generic delegate types Func and Action, so that you
don't need to define custom delegates manually in most cases.
Func is a generic delegate included in the System namespace. It has zero or
more input parameters and one out parameter. The last parameter is
considered as an out parameter .
The Func delegate that takes one input parameter and one out parameter
is defined in the System namespace, as shown below:
namespace System
{
public delegate TResult Func<in T, out TResult>(T arg);
}
Action Delegate:
Action is a delegate type defined in the System namespace. An Action type
delegate is the same as Func delegate except that the Action delegate doesn't
return a value. In other words, an Action delegate can be used with a method
that has a void return type.
Output:
10
Predicate Delegate:
Predicate is the delegate like Func and Action delegates. It represents a
method containing a set of criteria and checks whether the passed parameter
meets those criteria. A predicate delegate methods must take one input
parameter and return a boolean - true or false.
Same as other delegate types, Predicate can also be used with any method,
anonymous method, or lambda expression.
Example:
Console.WriteLine(result);
}
Output:
False
Anonymous Methods:
print(100);
}
Output:
Inside Anonymous method. Value: 100