0% found this document useful (0 votes)
14 views62 pages

Unit 3 Course

This document provides an overview of C# fundamentals, including creating a console application in Visual Studio, understanding reserved keywords, classes, namespaces, variables, data types, and working with strings and dates. It covers the syntax for defining classes and methods, creating objects, and the importance of namespaces in organizing code. Additionally, it explains the differences between value types (structs) and reference types (classes) in C#.

Uploaded by

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

Unit 3 Course

This document provides an overview of C# fundamentals, including creating a console application in Visual Studio, understanding reserved keywords, classes, namespaces, variables, data types, and working with strings and dates. It covers the syntax for defining classes and methods, creating objects, and the importance of namespaces in organizing code. Additionally, it explains the differences between value types (structs) and reference types (classes) in C#.

Uploaded by

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

Unit 3: C# Fundamentals

 Create Console Program in C#:


In this tutorial, you use Visual Studio to create and run a C# console app, and explore some
features of the Visual Studio integrated development environment (IDE). This tutorial is part 1
of a two-part tutorial series.

 In this tutorial, you:

 Create a Visual Studio project.


 Create a C# console app.
 Debug your app.
 Close your app.
 Inspect your complete code.
Open Visual Studio, and choose Create a new project in the Start window.

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.

 Reserved Keywords in C#:


 C# contains reserved words that have special meaning for the compiler. These
reserved words are called "keywords". Keywords cannot be used as an
identifier (name of a variable, class, interface, etc.).

abstract base as bool break catch case

byte char checked class const continue decimal

private protected public return readonly ref sbyte

explicit extern false finally fixed float for

foreach goto if implicit in in (generic int


modifier)

ulong ushort unchecked using unsafe virtual void

null object operator out out (generic override params


modifier)

default delegate do double else enum event

sealed short sizeof stackalloc static string struct

switch this throw true try typeof uint

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.

 Likewise, in object-oriented programming, a class defines some properties,


fields, events, methods, etc. A class defines the kinds of data and the
functionality their objects will have.

 Define a Class:
 In C#, a class can be defined by using the class keyword. Let's define a class
named 'Student'.

 Example: Define a Class

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;

public int StudentId


{
get { return id; }
set { id = value; }
}
}
 Method
A method can contain one or more statements to be executed as a single unit. A
method may or may not return a value. A method can have one or more input
parameters.
public int Sum(int num1, int num2)
{
var total = num1 + num2;
return total;
}
 Objects of a Class
 You can create one or more objects of a class. Each object can have
different values of properties and field but methods and events behaves
the same.

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

 Example: Create an Object of a Class


Student mystudent = new Student();
You can now access public members of a class using the object.MemberName
notation.

 Example: Access Members of a Class


Student mystudent = new Student();
mystudent.FirstName = "Steve";
mystudent.LastName = "Jobs";

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";

Student mystudent2 = new Student();


mystudent2.FirstName = "Bill";
mystudent2.LastName = "Gates";
 Namespaces in C#:

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

 A namespace is a container for classes and namespaces. The namespace also


gives unique names to its classes thereby you can have the same class name in
different namespaces.

In C#, a namespace can be defined using the namespace keyword.

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.

 Example: Expressions with Variable


x + 20
y*2
z/2
 The result of the above expression depends on the value of x, y and z. For
example, if x = 5 then the result of x + 20 would be 25 and if x = 20 then the
result of x + 20 would be 40. In the same way, the result of y * 2 depends on
the value of y and the result of z/2 depends on the value of z. Here, x, y, z are
called variables because their values can be changed.
 Syntax

<data type> <variable name> = <value>;

int num = 100;


float rate = 10.2f;
decimal amount = 100.50M;
char code = 'C';
bool isValid = true;
string name = "Steve";

 The followings are naming conventions for declaring variables in C#:

 Variable names must be unique.


 Variable names can contain letters, digits, and the underscore _ only.
 Variable names must start with a letter.
 Variable names are case-sensitive, num and Num are considered different
names.
 Variable names cannot contain reserved keywords. Must prefix @ before
keyword if want reserve keywords as identifiers;

 Variables can be declared first and initialized later.


Example: Late Initialization
int num;
num = 100;
 Create Variables using var:
 C# var keyword initializes variables with var support. The data type of a var
variable will be determined when assigning values to variables.
 The following program will automatically cast the variable. And of course,
after assigning the variable value, the variable has a defined data type and
cannot be replaced.
 In the example below we have 3 variables declared with the var keyword. In
turn 3 variables are assigned values with the data types int, char and string.
After assigning values to variables it can be used as ordinary variables.

1. var varInt = 1;
2. var varChar = 'a';
3. var varString = "abcdef";

 Data Types in C#:


 C# is a strongly-typed language. It means we must declare the type of a
variable that indicates the kind of values it is going to store, such as integer,
float, decimal, text, etc.

 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.
Data Size Description
Type

int 4 bytes Stores whole numbers from -2,147,483,648 to


2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7


decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal


digits

bool 1 bit Stores true or false values

char 2 bytes Stores a single character/letter, surrounded by single quotes

string 2 bytes Stores a sequence of characters, surrounded by double


per quotes
character
• Working with Numbers in C#:
 Numbers, in general, can be divided into two types: Integer type and
floating-point types.
 Integer type numbers are whole numbers without decimal points. It can be
negative or positive numbers.
 Floating-point type is numbers with one or more decimal points. It can be
negative or positive numbers.
 C# includes different data types for integer types and floating-point types
based on their size in the memory and capacity to store 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;

 Floating Point Types:


 Floating-point numbers are positive or negative numbers with one or more
decimal points. C# includes three data types for floating-point numbers:
float, double, and decimal.

 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";

 A string variable can contain many words.

string greeting2 = "How are you!";

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

string s = "Hello how was your day!";


Console.WriteLine(s.Length);

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

 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.
 The default and the lowest value of a DateTime object is January 1, 0001
00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59
P.M.
 Use different constructors of the DateTime struct to assign an initial value to a
DateTime object.

//assigns default value 01/01/0001 00:00:00


DateTime dt1 = new DateTime();

//assigns year, month, day


DateTime dt2 = new DateTime(2015, 12, 31);

//assigns year, month, day, hour, min, seconds


DateTime dt3 = new DateTime(2015, 12, 31, 5, 10, 20);

 DateTime Static Fields:


 The DateTime struct includes static fields, properties, and methods. The
following example demonstrates important static fields and properties.
DateTime currentDateTime = DateTime.Now; //returns current date and time
DateTime todaysDate = DateTime.Today; // returns today's date
DateTime currentDateTimeUTC = DateTime.UtcNow; // returns current UTC date and time
 TimeSpan:
 TimeSpan is a struct that is used to represent time in days, hour, minutes,
seconds, and milliseconds.
DateTime dt = new DateTime(2015, 12, 31);
TimeSpan ts = new TimeSpan(25,20,55);
DateTime newDate = dt.Add(ts);

Console.WriteLine(newDate);//1/1/2016 1:20:55 AM

• Struct type in C#:


 C# Structs:
 In C#, classes and structs are blueprints that are used to create instance of
a class. Structs are used for lightweight objects such as Color, Rectangle,
Point etc.
 Unlike class, structs in C# are value type than reference type. It is useful if
you have data that is not intended to be modified after creation of struct.
using System;
public struct Rectangle
{
public int width, height;

}
public class TestStructs
{
public static void Main()
{

Rectangle r = new Rectangle();


r.width = 4;
r.height = 5;
Console.WriteLine("Area of Rectangle is: " + (r.width * r.height));
}

 Output:
Area of Rectangle is: 20

 C# Struct Example: Using Constructor and Method:


 Let's see another example of struct where we are using constructor to
initialize data and method to calculate area of rectangle.
using System;
public struct Rectangle
{

public int width, height;

public Rectangle(int w, int h)


{
width = w;

height = h;
}
public void areaOfRectangle() {
Console.WriteLine("Area of Rectangle is: "+(width*height)); }
}

public class TestStructs


{
public static void Main()
{
Rectangle r = new Rectangle(5, 6);
r.areaOfRectangle();
}
}

 Output:
Area of Rectangle is: 30

• Enum type in C#:


 An enum is a special "class" that represents a group of constants
(unchangeable/read-only variables).
 To create an enum, use the enum keyword (instead of class or interface),
and separate the enum items with a comma:
Syntax:
enum Enum_variable
{
string_1...;
string_2...;

.
.
}

 In above syntax, Enum_variable is the name of the enumerator, and


string_1 is attached with value 0, string_2 is attached value 1 and so on.
Because by default, the first member of an enum has the value 0, and the
value of each successive enum member is increased by 1. We can change
this default value.
using System;
namespace MyApplication
{

enum Level
{
Low,
Medium,
High

}
class Program
{
static void Main(string[] args)
{

Level myVar = Level.Medium;


Console.WriteLine(myVar);
}
}

Output:
Medium

enum Months
{

January, // 0
February, // 1
March, // 2
April, // 3
May, // 4
June, // 5
July // 6

static void Main(string[] args)


{
int myNum = (int) Months.April;

Console.WriteLine(myNum);
}

Output:
April

 StringBuilder over String in C#:


 Difference between String and StringBuilder in C#:
 In C#, both string and StringBuilder are used to represent text. However, there
is one key difference between them.
 In C#, a string is immutable. It means a string cannot be changed once created.
For example, a new string, "Hello World!" will occupy a memory space on the
heap. Now, changing the initial string "Hello World!" to "Hello World! from
Tutorials Teacher" will create a new string object on the memory heap instead
of modifying an original string at the same memory address. This impacts the
performance if you modify a string multiple times by replacing, appending,
removing, or inserting new strings in the original string.
 For example, the following create a new string object when you concatenate a
value to it.
 Example: String Copy
string greeting = "Hello World!";
greeting += " from Tutorials Teacher."; // creates a new string object
 In contrast, StringBuilder is a mutable type. It means that you can modify its
value without creating a new object each time.
 Example: StringBuilder Copy
StringBuilder sb = new StringBuilder("Hello World!");
sb.Append("from Tutorials Teacher."); //appends to the same object

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

 Operators are the foundation of any programming language. Thus the


functionality of C# language is incomplete without the use of operators.
Operators allow us to perform different kinds of operations on operands. In
C#, operators Can be categorized based upon their different functionality :
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Arithmetic Operators
 These are used to perform arithmetic/mathematical operations on operands.
The Binary Operators falling in this category are :

 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);

Console.WriteLine("Equal to Operator: " + result);

// Greater than Operator


result = (x > y);
Console.WriteLine("Greater than Operator: " + result);

// Less than Operator


result = (x < y);
Console.WriteLine("Less than Operator: " + result);

// Greater than Equal to Operator


result = (x >= y);
Console.WriteLine("Greater than or Equal to: "+ result);
// Less than Equal to Operator
result = (x <= y);
Console.WriteLine("Lesser than or Equal to: "+ result);

// Not Equal To Operator


result = (x != y);
Console.WriteLine("Not Equal to Operator: " + result);
}

}
}

Output:
Equal to Operator: False

Greater than Operator: False


Less than Operator: True
Greater than or Equal to: False
Lesser than or Equal to: True
Not Equal to Operator: True

 Logical Operators:

 They are used to combine two or more conditions/constraints or to


complement the evaluation of the original condition in consideration. They
are described below:
 Logical AND: The ‘&&’ operator returns true when both the conditions in
consideration are satisfied. Otherwise it returns false. For example, a && b
returns true when both a and b are true (i.e. non-zero).
 Logical OR: The ‘||’ operator returns true when one (or both) of the
conditions in consideration is satisfied. Otherwise it returns false. For
example, a || b returns true if one of a or b is true (i.e. non-zero). Of
course, it returns true when both a and b are true.
 Logical NOT: The ‘!’ operator returns true the condition in consideration is
not satisfied. Otherwise it returns false. For example, !a returns true if a is
false, i.e. when a=0.
Example:

// C# program to demonstrate the working


// of Logical Operators
using System;
namespace Logical {

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 AND Operator


result = x & y;
Console.WriteLine("Bitwise AND: " + result);

// Bitwise OR Operator

result = x | y;
Console.WriteLine("Bitwise OR: " + result);

// Bitwise XOR Operator


result = x ^ y;

Console.WriteLine("Bitwise XOR: " + result);


// Bitwise AND Operator
result = ~x;

Console.WriteLine("Bitwise Complement: " + result);

// Bitwise LEFT SHIFT Operator


result = x << 2;
Console.WriteLine("Bitwise Left Shift: " + result);

// Bitwise RIGHT SHIFT Operator


result = x >> 2;
Console.WriteLine("Bitwise Right Shift: " + result);

}
}
}

Output:
Bitwise AND: 0

Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -6
Bitwise Left Shift: 20
Bitwise Right Shift: 1
 Assignment Operators:

 Assignment operators are used to assigning a value to a variable. The left


side operand of the assignment operator is a variable and right side
operand of the assignment operator is a value. The value on the right side
must be of the same data-type of the variable on the left side otherwise the
compiler will raise an error.

 Different types of assignment operators are shown below:

 “=”(Simple Assignment): This is the simplest assignment operator. This


operator is used to assign the value on the right to the variable on the left.

Example:
a = 10;
b = 20;
ch = 'y';

 “+=”(Add Assignment): This operator is combination of ‘+’ and ‘=’ operators.


This operator first adds the current value of the variable on left to the value
on the right and then assigns the result to the variable on the left.

 Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.

 “-=”(Subtract Assignment): This operator is combination of ‘-‘ and ‘=’


operators. This operator first subtracts the current value of the variable on
left from the value on the right and then assigns the result to the variable
on the left.

 Example:

(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.

 “*=”(Multiply Assignment): This operator is combination of ‘*’ and ‘=’


operators. This operator first multiplies the current value of the variable on
left to the value on the right and then assigns the result to the variable on
the left.

 Example:

(a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.

 “/=”(Division Assignment): This operator is combination of ‘/’ and ‘=’


operators. This operator first divides the current value of the variable on
left by the value on the right and then assigns the result to the variable on
the left.

 Example:

(a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.

 “%=”(Modulus Assignment): This operator is combination of ‘%’ and ‘=’


operators. This operator first modulo the current value of the variable on
left by the value on the right and then assigns the result to the variable on
the left.
 Example:

(a %= b) can be written as (a = a % b)
If initially value stored in a is 6. Then (a %= 2) = 0.

 Partial Classes in C#:


 A partial class is a special feature of C#. It provides a special ability to
implement the functionality of a single class into multiple files and all these
files are combined into a single class file when the application is compiled. A
partial class is created by using a partial keyword. This keyword is also useful
to split the functionality of methods, interfaces, or structure into multiple files.
 Syntax :
public partial Clas_name
{
// code
}

 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);
}
}

 Above, EmployeeProps.cs contains properties of the Employee class, and


EmployeeMethods.cs contains all the methods of the Employee class.
These will be compiled as one Employee class.

 Example: Combined Class


public class Employee
{
public int EmpId { get; set; }
public string Name { get; set; }

public Employee(int id, string name){


this.EmpId = id;
this.Name = name;
}
public void DisplayEmpInfo(){
Console.WriteLine(this.EmpId + " " this.Name );
}
}

 Static types in C#:

 In C#, one is allowed to create a static class, by using static keyword.


A static class can only contain static data members, static methods,
and a static constructor.It is not allowed to create objects of the
static class. Static classes are sealed, means you cannot inherit a
static class from another class.

 Syntax:

static class Class_Name

// static data members


// static method
}

 In C#, the static class contains two types of static members as


follows:

 Static Data Members:

 As static class always contains static data members, so static data


members are declared using static keyword and they are directly
accessed by using the class name. The memory of static data
members is allocating individually without any relation with the
object.
 Syntax:
static class Class_name
{
public static nameofdatamember;

 Static Methods:

 As static class always contains static methods, so static methods


are declared using static keyword. These methods only access
static data members, they can not access non-static data
members.

 Syntax:
static class Class_name {

public static nameofmethod()


{
// code

}
}
 Difference between static and non-static class:

Static Class 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 does not contain an Non-static class contains an instance


instance constructor. constructor.

Static class cannot inherit from Non-static class can be inherited from
another class. another class.

 Object Initializer Syntax:


 In object initializer, you can initialize the value to the fields or properties of a
class at the time of creating an object without calling a constructor. In this
syntax, you can create an object and then this syntax initializes the freshly
created object with its properties, to the variable in the assignment. It can also
place indexers, to initializing fields and properties, this feature is introduced in
C# 6.0.
 Example: In the below example, Geeks class doesn’t contain any constructor,
we simply create the object and initialize the value at the same time using
curly braces in the main method. This initializing of values is known as object
initializer.
using System;

class Obj {

public string author_name


{
get;
set;
}
public int author_id
{
get;
set;
}
public int total_article
{
get;
set;
}
}

class obj1 {

// Main method
static public void Main()
{

// Initialize fields using


// an object initializer
Obj obj = new Geeks() {
author_name = "Ankita Saini",
author_id = 102,
total_article = 178};

Console.WriteLine("Author Name: {0}", obj.author_name);

Console.WriteLine("Author Id: {0}", obj.author_id);

Console.WriteLine("Total no of articles: {0}",


obj.total_article);
}
}

 Output:
Author Name: Ankita Saini
Author Id: 102
Total no of articles: 178

 Covariance and Contravariance:

 Covariance and contravariance allow us to be flexible when dealing with class


hierarchy.
 Consider the following class hierarchy before we learn about covariance and
contravariance:

 Example: Class Hierarchy


public class Small

{
}
public class Big: Small
{
}

public class Bigger : Big


{

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

bool result = i.IsGreaterThan(100); //returns false

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

 Example: Define an Extension Method


namespace ExtensionMethods

{
public static class IntExtensions
{
public static bool IsGreaterThan(this int i, int value)
{

return i > value;


}
}
}
 using ExtensionMethods;

class Program
{
static void Main(string[] args)

{
int i = 10;

bool result = i.IsGreaterThan(100);

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.

 finally block: The finally block will always be executed whether an


exception raised or not. Usually, a finally block should be used to release
resources, e.g., to close any stream or file objects that were opened in
the try block.

 Example: Exception handling using try-catch blocks


class Program
{

static void Main(string[] args)


{
try
{
Console.WriteLine("Enter a number: ");

var num = int.parse(Console.ReadLine());


Console.WriteLine($"Squre of {num} is {num * num}");
}
catch

{
Console.Write("Error occurred.");
}
finally
{

Console.Write("Re-try with a different number.");


}
}
}
Note:

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

 Ideally, a catch block should include a parameter of a built-in or custom


exception class to get an error detail. The following includes the
Exception type parameter that catches all types of exceptions.

 Example: Exception handling using try catch block


class Program
{
static void Main(string[] args)
{
try

{
Console.WriteLine("Enter a number: ");
var num = int.parse(Console.ReadLine());

Console.WriteLine($"Squre of {num} is {num * num}");


}
catch(Exception ex)
{
Console.Write("Error info:" + ex.Message);

}
finally
{
Console.Write("Re-try with a different number.");
}

}
}
 C# Conditions & Loops:

 if, else if, else Condition:


 In C#, as we know that if-statement is executed if the condition is true
otherwise it will not execute. But, what if we want to print/execute
something if the condition is false. Here comes the else statement. Else
statement is used with if statement to execute some block of code if the
given condition is false. Or in other words, in the if-else statement, if the
given condition evaluates to true, then the if condition executes, or if the
given condition evaluates to false, then the else condition will execute.
 Else-statement can contain single or multiple statements in the curly
braces{}. If the else statement only contains a single statement, then the
curly braces are optional.
 The statements of else-statement can be of any kind/type like it may
contain another if-else statement.

Syntax:
if(condition)
{
// code if condition is true
}

else
{
// code if condition is false
}
using System;

class Program{

static public void Main()


{

// Declaring and initializing variables


string x = "Hello";

string y = "How are you";

// If-else statement
if (x == y)
{

Console.WriteLine("Both strings are equal..!!");


}
// else statement
else
{
Console.WriteLine("Both strings are not equal..!!");
}
}
}

Output:
Both strings are not equal..!!
using System;

class Program{

static public void Main()


{

// Declaring and initializing variables


int x = 10;

int y = 100;

// If-else statement
if (x >= y)
{

Console.WriteLine("x is greater than 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:

condition ? statement 1 : statement 2

 The ternary operator starts with a boolean condition. If this condition


evaluates to true then it will execute the first statement after ?,
otherwise the second statement after : will be executed.

 The following example demonstrates the ternary operator.

int x = 20, y = 10;

var result = x > y ? "x is greater than y" : "x is less than y";

Console.WriteLine(result);

output:

x is greater than y

 Nested Ternary Operator:


 Nested ternary operators are possible by including a conditional
expression as a second statement.

int x = 10, y = 100;

string result = x > y ? "x is greater than y" :


x < y ? "x is less than y" :
x == y ? "x is equal to y" : "No result";

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 value1: // statement sequence


break;

case value2: // statement sequence


break;
.
.

.
case valueN: // statement sequence
break;

default: // default statement sequence

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

for (initializer; condition; iterator)

{
//code block
}

 Initializer: The initializer section is used to initialize a variable that


will be local to a for loop and cannot be accessed outside loop. It can
also be zero or more assignment statements, method call, increment,
or decrement expression e.g., ++i or i++, and await expression.

 Condition: The condition is a boolean expression that will return


either true or false. If an expression evaluates to true, then it will
execute the loop again; otherwise, the loop is exited.
 Iterator: The iterator defines the incremental or decremental of the
loop variable.

for(int i = 0; i < 10; i++)


{
Console.WriteLine("Value of i: {0}", i);

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

while (boolean condition)


{
loop statements...
}

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

 Nested while Loop


C# allows while loops inside another while loop, as shown below. However, it is
not recommended to use nested while loop because it makes it hard to debug
and maintain.
Example: Nested while Loop
int i = 0, j = 1;

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;

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

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.

 A multidimensional array is basically an array of 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} };

 Access Elements of a 2D Array:


 To access an element of a two-dimensional array, you must specify two
indexes: one for the array, and one for the element inside that array. Or
better yet, with the table visualization in mind; one for the row and one
for the column (see example below).

 This statement accesses the value of the element in the first row (0) and
third column (2) of the numbers array:

int[,] numbers = { {1, 4, 2}, {3, 6, 8} };


Console.WriteLine(numbers[0, 2]); // Outputs 2

 You can easily loop through the elements of a two-dimensional array


with a foreach loop:

 Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };

foreach (int i in numbers)


{
Console.WriteLine(i);
}

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

 Properties of ArrayList Class:


 Elements can be added or removed from the Array List collection at any
point in time.
 The ArrayList is not guaranteed to be sorted.
 The capacity of an ArrayList is the number of elements the ArrayList can
hold.
 Elements in this collection can be accessed using an integer index. Indexes
in this collection are zero-based.
 It also allows duplicate elements.
 Using multidimensional arrays as elements in an ArrayList collection is not
supported.

ArrayList arlist = new ArrayList();

 Use the Add() method or object initializer syntax to add elements in an


ArrayList.

 An ArrayList can contain multiple null and duplicate values.

var arlist1 = new ArrayList();


arlist1.Add(1);
arlist1.Add("Bill");
arlist1.Add(" ");
arlist1.Add(true);
arlist1.Add(4.5);
arlist1.Add(null);
 List:
 List<T> class represents the list of objects which can be accessed by index.
It comes under the System.Collections.Generic namespace. List class can be
used to create a collection of different types like integers, strings etc.
List<T> class also provides the methods to search, sort, and manipulate
lists.

 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);

var cities = new List<string>();


cities.Add("New York");
cities.Add("London");
cities.Add("Mumbai");
cities.Add("Chicago");
cities.Add(null);// nulls are allowed for reference type list
 C# Events & Delegates:
• What is Delegates?
 A delegate is an object which refers to a method or you can say it is a
reference type variable that can hold a reference to the methods.
Delegates in C# are similar to the function pointer in C/C++. It provides a
way which tells which method is to be called when an event is triggered.
 For example, if you click on a Button on a form (Windows Form
application), the program would call a specific method. In simple words, it
is a type that represents references to methods with a particular parameter
list and return type and then calls the method in a program for execution
when it is needed.

 Important Points About Delegates:

 Provides a good way to encapsulate the methods.


 Delegates are the library class in System namespace.
 These are the type-safe pointer of any method.
 Delegates are mainly used in implementing the call-back methods and
events.
 Delegates can be chained together as two or more methods can be called
on a single event.
 It doesn’t care about the class of the object that it references.
 Delegates can also be used in “anonymous methods” invocation.
 Anonymous Methods(C# 2.0) and Lambda expressions(C# 3.0) are compiled
to delegate types in certain contexts. Sometimes, these features together
are known as anonymous functions.

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

 For example, the following delegate prints an int value.

public delegate void Print(int val);

static void ConsolePrint(int i)


{
Console.WriteLine(i);
}

static void Main(string[] args)


{
Print prnt = ConsolePrint;
prnt(10);
}

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

 The Predicate delegate is defined in the System namespace, as shown below:

 Predicate signature: public delegate bool Predicate<in T>(T obj);

 Same as other delegate types, Predicate can also be used with any method,
anonymous method, or lambda expression.

 Example:

static bool IsUpperCase(string str)


{
return str.Equals(str.ToUpper());
}

static void Main(string[] args)


{
Predicate<string> isUpper = IsUpperCase;

bool result = isUpper("hello world!!");

Console.WriteLine(result);
}
 Output:

False

 Anonymous Methods:

 As the name suggests, an anonymous method is a method without a name.


Anonymous methods in C# can be defined using the delegate keyword and
can be assigned to a variable of delegate type.

public delegate void Print(int value);

static void Main(string[] args)


{
Print print = delegate(int val) {
Console.WriteLine("Inside Anonymous method. Value: {0}", val);
};

print(100);
}

 Output:
Inside Anonymous method. Value: 100

You might also like