Chapter 3 lab report
Chapter 3 lab report
DECLARE Delegate:
public delegate void MyDelegate(string msg);
Set Delegate Target:
public delegate void MyDelegate(string msg); // declare a delegate
// 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;
class DelegateExample
{
static void Main(string[] args)
{
MyDelegate del = ClassA.MethodA;
del("Hello World");
del = ClassB.MethodB;
del("Hello World");
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
using System;
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
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
• 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);
Console.ReadLine();
}
}
}
Lambda Expression
using System;
class LambdaEx1
{
static void Main(String[] args)
{
// expression lambda that returns the square of a number
var square = (int num) => num * num;
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;
};
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
Note: How Can User defined Exception Handling define and use?
Introduction to LINQ
// 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
• 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 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"
};
// 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 }
};
// 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 }
};