0% found this document useful (0 votes)
25 views8 pages

C# - Unit III

Uploaded by

pubgmobilesd23
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)
25 views8 pages

C# - Unit III

Uploaded by

pubgmobilesd23
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/ 8

UNIT III – C# ADVANCED FEATURES

3.1 C# Delegates
In C#, delegate is a reference to the method. It works like function pointer in C and C++. But it is
objected-oriented, secured and type-safe than function pointer.

For static method, delegate encapsulates method only. But for instance method, it encapsulates method
and instance both.

using System;
delegateint Calculator(int n);//declaring delegate
public class DelegateExample
{
staticint number = 100;
public static int add(int n)
{ number = number + n; return number; }
public static intmul(int n)
{ number = number * n; return number; }
public static intgetNumber()
{ return number; }
public static void Main(string[] args)
{
Calculator c1 = new Calculator(add);//instantiating delegate
Calculator c2 = new Calculator(mul);
c1(20);//calling method using delegate
Console.WriteLine("After c1 delegate, Number is: " + getNumber());
c2(3);
Console.WriteLine("After c2 delegate, Number is: " + getNumber());
} }

3.2 C# 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 * 7

Here, num is an input parameter and num * 7 is a return value. The lambda expression does not execute
on its own. Instead, we use it inside other methods or variables.
Let's learn about lambda expressions in detail below.
How to Define a Lambda Expression
We can define lambda expression in C# as,
(parameterList) =>lambda body

Here,
 parameterList - list of input parameters
 => - a lambda operator
 lambda body - can be an expression or statement

Based on lambda body, the C# lambda expression is divided into two types.

Types of Lambda Expression


The two types of lambda expressions are:
1. Expression Lambda
2. Statement Lambda

1. Expression Lambda: Expression lambda contains a single expression in the lambda body. For
example,
(intnum) =>num * 5;
The above expression lambda contains a single expression num * 5 in the lambda body. It takes an int
input, multiplies it by 5, and returns the output.

2. Statement Lambda: Statement lambda encloses one or more statements in the lambda body. We use
curly braces {} to wrap the statements. For example,
(int a, int b) =>
{ var sum = a + b; return sum; };

Example: C# Expression Lambda


using System;
classProgram
{
staticvoidMain()
{
var square = (intnum) =>num * num;
Console.WriteLine("Square of number: " + square(5));
}}
Example: C# Statement Lambda
using System;
class Program
{
static void Main()
{
varresultingSum = (int a, int b) =>
{
intcalculatedSum = a + b;
returncalculatedSum;
};
Console.WriteLine("Total sum: " + resultingSum(5, 6));
}
}

3.3 C# - 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.
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 −
eventBoilerLogHandlerBoilerEventLog;
The preceding code defines a delegate named BoilerLogHandler and an event named BoilerEventLog,
which invokes the delegate when it is raised.

using System;
namespaceSampleApp {
public delegate string MyDel(string str);
classEventProgram {
eventMyDelMyEvent;
publicEventProgram() {
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("Tutorials Point");
Console.WriteLine(result);
}
}
}

3.4 C# - Regular Expressions


A regular expression is a pattern that could be matched against an input text. The .Net
framework provides a regular expression engine that allows such matching. A pattern consists of one or
more character literals, operators, or constructs.

Constructs for Defining Regular Expressions


There are various categories of characters, operators, and constructs that lets you to define regular
expressions. Click the following links to find these constructs.
 Character escapes
 Character classes
 Anchors
 Grouping constructs
 Quantifiers
 Backreference constructs
 Alternation constructs
 Substitutions
using System;
usingSystem.Text.RegularExpressions;
namespaceRegExApplication {
class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) {
Console.WriteLine(m);
}
}
static void Main(string[] args) {
stringstr = "A Thousand Splendid Suns";
Console.WriteLine("Matching words that start with 'S': ");
showMatch(str, @"\bS\S*");
Console.ReadKey();
}
} }

3.5 C# Collections
In C#, collection represents group of objects. By the help of collections, we can perform various
operations on objects such as
 store object
 update object
 delete object
 retrieve object
 search object, and
 sort object

In sort, all the data structure work can be performed by C# collections.


We can store objects in array or collection. Collection has advantage over array. Array has size limit but
objects stored in collection can grow or shrink dynamically.

Types of Collections in C#
There are 3 ways to work with collections. The three namespaces are given below:
 System.Collections.Generic classes
 System.Collections classes (Now deprecated)
 System.Collections.Concurrent classes
1) System.Collections.Generic classes
The System.Collections.Generic namespace has following classes:
 List
 Stack
 Queue
 LinkedList
 HashSet
 SortedSet
 Dictionary
 SortedDictionary
 SortedList

2) System.Collections classes
These classes are legacy. It is suggested now to use System.Collections.Generic classes. The
System.Collections namespace has following classes:
 ArrayList
 Stack
 Queue
 Hashtable

3) System.Collections.Concurrent classes
The System.Collections.Concurrent namespace provides classes for thread-safe operations. Now multiple
threads will not create problem for accessing the collection items.
The System.Collections.Concurrent namespace has following classes:
 BlockingCollection
 ConcurrentBag
 ConcurrentStack
 ConcurrentQueue
 ConcurrentDictionary
 Partitioner
 Partitioner
 OrderablePartitioner

3.6 C# Memory Management

Resource Allocation
The Microsoft .NET common language runtime requires that all resources be allocated from the
managed heap. Objects are automatically freed when they are no longer needed by the application.
When a process is initialized, the runtime reserves a contiguous region of address space that
initially has no storage allocated for it. This address space region is the managed heap. The heap also
maintains a pointer. This pointer indicates where the next object is to be allocated within the heap.
Initially, the pointer is set to the base address of the reserved address space region.
An application creates an object using the new operator. This operator first ensures that the bytes
required by the new object fit in the reserved region (committing storage if necessary). If the object fits,
then the pointer points to the object in the heap, this object's constructor is called, and the new operator
returns the address of the object.
When an application calls the new operator to create an object, there may not be enough address
space left in the region to allocate to the object. The heap detects this by adding the size of the new object
to NextObjPtr. If NextObjPtr is beyond the end of the address space region, then the heap is full and a
collection must be performed.
In reality, a collection occurs when generation 0 is completely full. Briefly, a generation is a
mechanism implemented by the garbage collector to improve performance. The idea is that newly created
objects are part of a young generation, and objects created early in the application's lifecycle are in an old
generation. Separating objects into generations can allow the garbage collector to collect specific
generations instead of collecting all objects in the managed heap.

3.7 C# - Reflection
Reflection objects are used for obtaining type information at runtime. The classes that give
access to the metadata of a running program are in the System.Reflection namespace.

The System.Reflection namespace contains classes that allow you to obtain information about
the application and to dynamically add types, values, and objects to the application.

Applications of Reflection
Reflection has the following applications −
 It allows view attribute information at runtime.
 It allows examining various types in an assembly and instantiate these types.
 It allows late binding to methods and properties
 It allows creating new types at runtime and then performs some tasks using those types.

Viewing Metadata
We have mentioned in the preceding chapter that using reflection you can view the attribute information.
The MemberInfo object of the System.Reflection class needs to be initialized for discovering the
attributes associated with a class. To do this, you define an object of the target class, as −
System.Reflection.MemberInfo info =typeof(MyClass);
using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute {
publicreadonly string Url;
public string Topic // Topic is a named parameter {
get {return topic; }
set { topic = value; }
}
publicHelpAttribute(string url) { this.Url = url; }
private string topic;
}

[HelpAttribute("Information on the class MyClass")]


classMyClass {}
namespaceAttributeAppl {
class Program {
static void Main(string[] args) {
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);

for (inti = 0; i<attributes.Length; i++) {


System.Console.WriteLine(attributes[i]);
}
Console.ReadKey();
}
}
}

You might also like