0% found this document useful (0 votes)
21 views51 pages

Chapter 3 lab report

Uploaded by

my689013
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)
21 views51 pages

Chapter 3 lab report

Uploaded by

my689013
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/ 51

Advance C#

Er. Riddhi K. Shrestha


Delegates

• C# delegates are similar to pointers to functions, in C or


C++.
• A delegate is a reference type variable that holds the
reference to a method.
• The reference can be changed at runtime.
• Delegates are especially used for implementing events and
the call-back methods.
• All delegates are implicitly derived from the
System.Delegate class.
Delegates

• The delegate is a reference type data type that defines the


method signature.
• We can define variables of delegate, just like other data
type, that can refer to any method with the same signature
as the delegate.
• Three steps involved while working with delegates:
• Declare a delegate
• Create an instance and reference a method
• Invoke a delegate
• A delegate can be declared using the delegate keyword
followed by a function signature.
[access modifier] delegate [return type] [delegate
name]([parameters])
Delegates

DECLARE Delegate:
public delegate void MyDelegate(string msg);
Set Delegate Target:
public delegate void MyDelegate(string msg); // declare a delegate

// set target method


MyDelegate del = new MyDelegate(MethodA);
// or
MyDelegate del = MethodA;
// or set lambda expression
MyDelegate del = (string msg) => Console.WriteLine(msg);

// target method
static void MethodA(string message)
{
Console.WriteLine(message);
}
Delegates

Invoke a Delegate:
del.Invoke("Hello World!");
// or
del("Hello World!");
Delegates
using System;

public delegate void MyDelegate(string msg); //declaring a delegate

class DelegateExample
{
static void Main(string[] args)
{
MyDelegate del = ClassA.MethodA;
del("Hello World");

del = ClassB.MethodB;
del("Hello World");

del = (string msg) => Console.WriteLine("Called lambda


expression: " + msg);
del("Hello World");
}
}
Delegates

class ClassA
{
static void MethodA(string message)
{
Console.WriteLine("Called ClassA.MethodA() with parameter: " +
message);
}
}

class ClassB
{
static void MethodB(string message)
{
Console.WriteLine("Called ClassB.MethodB() with parameter: " +
message);
}
}
Events

• Events are user actions such as key press, clicks,


mouse movements, etc., or some occurrence such as
system generated notifications.
• Applications need to respond to events when they
occur.
• For example, interrupts. Events are used for inter-
process communication.
Using Delegates with Events

• The events are declared and raised in a class and


associated with the event handlers using delegates
within the same class or some other class.
• The class containing the event is used to publish the
event. This is called the publisher class. Some other
class that accepts this event is called the subscriber
class. Events use the publisher-subscriber model.
Using Delegates with Events

• A publisher is an object that contains the definition of the


event and the delegate. The event-delegate association is
also defined in this object. A publisher class object invokes
the event and it is notified to other objects.
• A subscriber is an object that accepts the event and
provides an event handler. The delegate in the publisher
class invokes the method (event handler) of the subscriber
class.
Declaring Events

• To declare an event inside a class, first of all, you


must declare a delegate type for the even as:
public delegate string BoilerLogHandler(string str);
• then, declare the event using the event keyword −
event BoilerLogHandler BoilerEventLog;
Declaring Events

using System;

public delegate string MyDel(string str);

class EventProgram {
event MyDel MyEvent;

public EventProgram() {
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username) {
return "Welcome " + username;
}
static void Main(string[] args) {
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("St. Lawarance College");
Console.WriteLine(result);
}
}
Indexers

• An indexer allows us to access instances of a class using an


index just like an array.
• In C#, we define an indexer just like properties using
this keyword followed by [] index notation. For
example,
public int this[int index]
{
get
{
return val[index];
}

set
{
val[index] = value;
}
}
Indexers : Example

using System;
class IndexerExample
{
// declare an array to store elements
private string[] studentName = new string[10];

// define an indexer
public string this[int index]
{
get
{
// return value of stored at studentName array
return studentName[index];
}

set
{
// assigns value to studentName
studentName[index] = value;
}
}
Indexers : Example

public static void Main(String[] args)


{
// create instance of Program class
IndexerExample obj = new IndexerExample();

// insert values in obj[] using indexer i.e index position


obj[0] = "Gopal";
obj[1] = "Hari";
obj[2] = "Nepal";

Console.WriteLine("First element in obj: " + obj[0]);


Console.WriteLine("Second element in obj: " + obj[1]);
}
}
Properties

• Properties are named members of classes, structures, and


interfaces.
• Member variables or methods in a class or structures are
called Fields.
• Properties are an extension of fields and are accessed using
the same syntax.
• They use accessors through which the values of the private
fields can be read, written or manipulated.
• Properties do not name the storage locations. Instead, they
have accessors that read, write, or compute their values.
• For example, let us have a class named Student, with private fields
for age, name, and code. We cannot directly access these fields from
outside the class scope, but we can have properties for accessing
these private fields.
Properties - Accessors

• The accessor of a property contains the executable


statements that helps in getting (reading or computing) or
setting (writing) the property.
• The accessor declarations can contain a get accessor, a set
accessor, or both. For example −
// Declare a Code property of type string:
public string Code {
get {
return code;
}
set {
code = value;
}
}

// Declare a Name property of type string:


public string Name {
get {
return name;
}
set {
name = value;
}
}
Properties - Accessors

// Declare a Age property of type int:


public int Age {
get {
return age;
}
set {
age = value;
}
}
Properties : Example
// Declare a Age property of type int:
using System; public int Age {
class Student { get {
private string code = "N.A"; return age;
private string name = "not known"; }
private int age = 0; set {
age = value;
// Declare a Code property of type string: }
public string Code { }
get { public override string ToString() {
return code; return "Code = " + Code +", Name = " + Name +
} ", Age = " + Age;
set { }
code = value; }
}
} class ExampleDemo {
public static void Main(String[] args) {
// Declare a Name property of type string:
public string Name { // Create a new Student object:
get { Student s = new Student();
return name;
} // Setting code, name and the age of the student
set { s.Code = "001";
name = value; s.Name = "Zara";
} s.Age = 9;
} Console.WriteLine("Student Info: {0}", s);

//let us increase age


s.Age += 1;
Console.WriteLine("Student Info: {0}", s);
Console.ReadKey();
}}
Generics

• Generics in C# are a way to create code that can be used


with different data types.
• This makes the code more versatile and reusable. Generics
are declared using the <> symbol.
• For example, the following code declares a generic method
called Print:
public static void Print<T>(T value)
{
Console.WriteLine(value);
}
• This method can be used to print any data. For example,
the following code prints an integer and a string:
Print(10);
Print("Hello, world!");
Generics

• Generics can also be used to create generic classes. For


example, the following code declares a generic class called
List:
public class List<T> This class can be used to store any data type. For
{ example, the following code creates a list of integers and
private T[] items;
adds some numbers to it:
public List() List<int> numbers = new List<int>();
{ numbers.Add(10);
items = new T[0]; numbers.Add(20);
}
numbers.Add(30);
public void Add(T item)
{
items = Array.Resize(items, items.Length + 1);
items[items.Length - 1] = item;
}

public T Get(int index)


{
return items[index];
}
}
Advantage of Generics

• They make code more versatile. Generic code can be used with
different data types, which makes it more reusable.
• They make code more concise. Generic code can often be
written more concisely than non-generic code.
• They can improve performance. Generic code can sometimes
improve performance by eliminating the need for type casts.
• They can help to prevent errors. Generic code can help
prevent errors by ensuring the correct data types are used.
Generic Classes

• The Generic class can be defined by putting the <T> sign after the class
name. Putting the "T" word in the Generic type definition isn't
mandatory. You can use any word in the TestClass<> class declaration.
public class TestClass<T> { }
• The System.Collection.Generic namespace also defines a number of
classes that implement many of these key interfaces. The following table
describes the core class types of this namespace.
Generic Classes : Example
class Program
using System;
using System.Collections.Generic;
{
static void Main(string[] args)
namespace GenericApp {
{ //instantiate generic with Integer
public class TestClass<T> TestClass<int> intObj = new TestClass<int>();
{
// define an Array of Generic type with length 5
T[] obj = new T[5];
//adding integer values into collection
int count = 0; intObj.Add(1);
intObj.Add(2);
// adding items mechanism into generic type intObj.Add(3); //No boxing
public void Add(T item) intObj.Add(4);
{ intObj.Add(5);
//checking length
if (count + 1 < 6)
{ //displaying values
obj[count] = item; for (int i = 0; i < 5; i++)
} {
count++; Console.WriteLine(intObj[i]); //No unboxing
} }
//indexer for foreach statement iteration
public T this[int index]
Console.ReadKey();
{ }
get { return obj[index]; } }
set { obj[index] = value; } }
}
}
Generic Methods : Example
using System;
using System.Collections.Generic;

namespace GenericApp
{
class Program
{
//Generic method
static void Swap<T>(ref T a, ref T b)
{
T temp;
temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
// Swap of two integers.
int a = 40, b = 60;
Console.WriteLine("Before swap: {0}, {1}", a, b);

Swap<int>(ref a, ref b);

Console.WriteLine("After swap: {0}, {1}", a, b);

Console.ReadLine();
}
}
}
Lambda Expression

• C# Lambda Expression is a short block of code that accepts


parameters and returns a value.
• It is defined as an anonymous function (function without a
name). For example, num => num * 3
• Here, num is an input parameter and num * 3 is a
return value. The lambda expression does not execute
on its own. Instead, we use it inside other methods or
variables. => is a lambda operator
• We can define lambda expression, (parameterList) =>
lambda body
Lambda Expression : Example

using System;
class LambdaEx1
{
static void Main(String[] args)
{
// expression lambda that returns the square of a number
var square = (int num) => num * num;

// passing input to the expression lambda


Console.WriteLine("Square of number: " + square(5));
}}
Lambda Expression : Example

using System;
class LambdaEx2
{
static void Main(String[] args)
{
// statement lambda that takes two int inputs and returns the sum
var resultingSum = (int a, int b) =>
{
int calculatedSum = a + b;
return calculatedSum;
};

// find the sum of 5 and 6


Console.WriteLine("Total sum: " + resultingSum(5, 6));
}
}
Exception Handling

• An exception is a problem that arises during the execution


of a program.
• A C# exception is a response to an exceptional
circumstance that arises while a program is running, such
as an attempt to divide by zero.
• Exceptions provide a way to transfer control from one
part of a program to another.
• C# exception handling is built upon four keywords: try,
catch, finally, and throw.
Exception Handling

• try − A try block identifies a block of code for which


particular exceptions is activated. It is followed by one or
more catch blocks.
• catch − A program catches an exception with an exception
handler at the place in a program where you want to
handle the problem. The catch keyword indicates the
catching of an exception.
• finally − The finally block is used to execute a given set of
statements, whether an exception is thrown or not thrown.
For example, if you open a file, it must be closed whether
an exception is raised or not.
• throw − A program throws an exception when a problem
shows up. This is done using a throw keyword.
Exception Handling : Syntax

try {
// statements causing exception
} catch( ExceptionName e1 ) {
// error handling code
} catch( ExceptionName e2 ) {
// error handling code
} catch( ExceptionName eN ) {
// error handling code
} finally {
// statements to be executed
}
Exception Handling : Example

using System;

class DivNumbersEx {
int result;

DivNumbersEx() {
result = 0;
}
public void division(int num1, int num2) {
try {
result = num1 / num2;
} catch (DivideByZeroException e) { //refer to official
documentation for other exception classes
Console.WriteLine("Exception caught: {0}", e);
} finally {
Console.WriteLine("Result: {0}", result);
}
}
Exception Handling : Example

static void Main(string[] args) {


DivNumbersEx d = new DivNumbersEx();
d.division(25, 0);
Console.ReadKey();
}
}
Exception Handling

Note: How Can User defined Exception Handling define and use?
Introduction to LINQ

• Language-Integrated Query (LINQ) is a powerful set of technologies


based on the integration of query capabilities directly into the C#
language.
• LINQ Queries are the first-class language construct in C# .NET, just like
classes, methods, events.
• The LINQ provides a consistent query experience to query objects (LINQ
to Objects), relational databases (LINQ to SQL), and XML (LINQ to
XML).
• LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to
retrieve data from different sources and formats.
• It is integrated in C# or VB, thereby eliminating the mismatch between
programming languages and databases, as well as providing a single querying
interface for different types of data sources.
• For example, SQL is a Structured Query Language used to save and retrieve
data from a database. In the same way, LINQ is a structured query syntax built
in C# and VB.NET to retrieve data from different types of data sources such as
collections, ADO.Net DataSet, XML Docs, web service and MS SQL Server and
other databases.
Introduction to LINQ

• Language-Integrated Query (LINQ) is a powerful set of technologies


based on the integration of query capabilities directly into the C#
language.
• LINQ Queries are the first-class language construct in C# .NET, just like
classes, methods, events.
• The LINQ provides a consistent query experience to query objects (LINQ
to Objects), relational databases (LINQ to SQL), and XML (LINQ to
XML).
• LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to
retrieve data from different sources and formats.
• It is integrated in C# or VB, thereby eliminating the mismatch between
programming languages and databases, as well as providing a single querying
interface for different types of data sources.
• For example, SQL is a Structured Query Language used to save and retrieve
data from a database. In the same way, LINQ is a structured query syntax built
in C# and VB.NET to retrieve data from different types of data sources such as
Introduction to LINQ

• LINQ queries return results as objects.


• It enables you to uses object-oriented approach on the result set and
not to worry about transforming different formats of results into
objects.

• The following example demonstrates a simple LINQ query that gets


all strings from an array which contains 'a’.
// Data source
string[] names = {"Bill", "Steve", "James", “Rohan" };

// LINQ Query
var myLinqQuery = from name in names
where name.Contains('a')
select name;

// Query execution
foreach(var name in myLinqQuery)
Console.Write(name + " ");
LINQ API in .NET

• We can write LINQ queries for the classes that implement


IEnumerable<T> or IQueryable<T> interface.
• The System.Linq namespace includes the different classes and
interfaces require for LINQ queries.
• LINQ queries uses extension methods for classes that implement
IEnumerable or IQueryable interface.
• The Enumerable and Queryable are two static classes that contain
extension methods to write LINQ queries.
Enumerable

• The Enumerable class includes extension methods for the classes that
implement IEnumerable<T> interface, for example all the built-in
collection classes implement IEnumerable<T> interface and so we can
write LINQ queries to retrieve data from the built-in collections.
• The following figure shows the extension methods included in
Enumerable class that can be used with the generic collections in C# or
VB.Net.
Enumerable

• The following figure shows all the extension methods


available in Enumerable class.
Queryable

• The Queryable class includes extension methods for classes that


implement IQueryable<t> interface.
• The IQueryable<T> interface is used to provide querying capabilities
against a specific data source where the type of the data is known.
• For example, Entity Framework api implements IQueryable<T> interface
to support LINQ queries with underlaying databases such as MS SQL
Server.
• The following figure shows the extension methods available in the
Queryable class can be used with various native or third party data
providers.
Queryable

• The following figure shows the extension


methods available in the Queryable class.
LINQ Query Syntax

• There are two basic ways to write a LINQ query to IEnumerable


collection or IQueryable data sources.
• Query Syntax or Query Expression Syntax
• Method Syntax or Method Extension Syntax or Fluent
Query Syntax

• Query syntax is similar to SQL (Structured Query Language) for the


database.
• It is defined within the C# or VB code.
• Syntax:
from <range variable> in <IEnumerable<T> or IQueryable<T>
Collection>

<Standard Query Operators> <lambda expression>

<select or groupBy operator> <result formation>


Query Syntax

• The LINQ query syntax starts with from keyword and ends with select
keyword.
• The following is a sample LINQ query that returns a collection of
strings which contains a word "Tutorials".
// string collection
IList<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};

// LINQ Query Syntax


var result = from s in stringList
where s.Contains("Tutorials")
select s;
Query Syntax : Example

// Student collection
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};

// LINQ Query Syntax to find out teenager students


var teenAgerStudent = from s in studentList
where s.Age > 12 && s.Age < 20
select s;
Method Syntax

• Method syntax (also known as fluent syntax) uses extension methods


included in the Enumerable or Queryable static class, similar to how
you would call the extension method of any class.
• The compiler converts query syntax into method syntax at compile
time.
• The following is a sample LINQ method syntax query that returns a
collection of strings which contains a word "Tutorials".
// string collection
IList<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};

// LINQ Method Syntax


var result = stringList.Where(s => s.Contains("Tutorials"));
Method Syntax : Example

// Student collection
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};

// LINQ Method Syntax to find out teenager students


var teenAgerStudents = studentList.Where(s => s.Age > 12 && s.Age < 20)
.ToList<Student>();
Standard Query Operators

• Standard Query Operators in LINQ are actually extension methods for


the IEnumerable<T> and IQueryable<T> types.
• They are defined in the System.Linq.Enumerable and
System.Linq.Queryable classes.
• There are over 50 standard query operators available in LINQ that
provide different functionalities like filtering, sorting, grouping,
aggregation, concatenation, etc.
Standard Query Operators

• Standard Query Operators in LINQ are actually extension methods for


the IEnumerable<T> and IQueryable<T> types.
• They are defined in the System.Linq.Enumerable and
System.Linq.Queryable classes.
• There are over 50 standard query operators available in LINQ that
provide different functionalities like filtering, sorting, grouping,
aggregation, concatenation, etc.
Standard Query Operators

Note : follow the official documentation https://learn.microsoft.com/en-


us/dotnet/csharp/linq/

You might also like