Unit 4 BCA
Unit 4 BCA
Delegates
A delegate is an object that knows how to call a method.
A delegate type defines the kind of method that delegate instances can call. Specifically, it
defines the method’s return type and its parameter types.
Delegates are especially used for implementing events and the call-back methods. All
delegates are implicitly derived from the System.Delegate class. It provides a way which
tells which method is to be called when an event is triggered.
For example, if you click an 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.
Declaring 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]);
modifier: It is the required modifier which defines the access of delegate and it is optional
to use. delegate: It is the keyword which is used to define the delegate. return_type: It is
the type of value returned by the methods which the delegate will be going to call. It can
be void. A method must have the same return type as the delegate.
delegate_name: It is the user-defined name or identifier for the delegate.
parameter_list: This contains the parameters which are required by the method when
called through the delegate.
Note: A delegate will call only a method which agrees with its signature and return type.
A method can be a static method associated with a class or can be an instance method
associated with an object, it doesn’t matter.
Transformer is compatible with any method with an int return type and a single int
parameter, such as this:
static int Square (int x) { return x * x; }
or
static int Square (int x) => x * x;
Output:
Result is : 25
Example 2
using System;
Output:
Value of Num: 35
Value of Num: 175
Example 3
class Test
{
public delegate void addnum(int a, int b);
public delegate void subnum(int a, int b);
// method "sum"
public void sum(int a, int b)
{
Console.WriteLine("(100 + 40) = {0}", a + b);
}
// method "subtract" public
void subtract(int a, int b)
{
Console.WriteLine("(100 - 60) = {0}", a - b);
}
// Main Method
public static void Main(String[] args)
{
addnum del_obj1 = new addnum(obj.sum);
subnum del_obj2 = new subnum(obj.subtract);
Output:
(100 + 40) = 140
(100 - 60) = 40
Multicast Delegates
All delegate instances have multicast capability. This means that a delegate instance can
reference not just a single target method, but also a list of target methods.
The + and += operators combine delegate instances. For example:
SomeDelegate d = SomeMethod1; d +=
SomeMethod2;
The - and -= operators remove the right delegate operand from the left delegate
operand.
For example:
d -= SomeMethod1;
Invoking d will now cause only SomeMethod2 to be invoked.
using System;
nc = nc1;
nc += nc2;
//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
Output
Value of Num: 75
Delegates Mapping with Instance and Static Method
Created ClassA contains instance & static method,
Output
Instance Method
Static Method
So using delegate, we can associate instance and static method under same delegate
instance.
Delegates Vs Interfaces in C#
Delegate Compatibility
Type compatibility
Delegate types are all incompatible with one another, even if their signatures are the
same:
Delegate instances are considered equal if they have the same method targets:
Parameter compatibility
When you call a method, you can supply arguments that have more specific types than
the parameters of that method. This is ordinary polymorphic behaviour. For exactly the
same reason, a delegate can have more specific parameter types than its method target.
This is called contravariance.
In this case, the String Action is invoked with an argument of type string. When the
argument is then relayed to the target method, the argument gets implicitly up cast to an
object.
Action<>
• This Action<> generic delegate; points to a method that takes up to 16 Parameters
and returns void.
Func<>
• The generic Func<> delegate is used when we want to point to a method that
returns a value.
• This delegate can point to a method that takes up to 16 Parameters and returns a
value.
• Always remember that the final parameter of Func<> is always the return value of
the method. (For example, Func< int, int, string>, this version of the Func<>
delegate will take 2 int parameters and returns a string value.)
class MethodCollections
{
//Methods that takes parameters but returns nothing:
}
public static int ShowNumber()
{
Random r = new Random();
return r.Next();
}
}
class Program
{
static void Main(string[] args)
{
Action printText = new Action(MethodCollections.PrintText);
Action<string> print = new Action<string>(MethodCollections.Pr int);
Action<int, int> printNumber = new Action<int, int>(MethodColl
ections.PrintNumbers);
Func<int, int,int> add1 = new Func<int, int, int>(MethodCollec
tions.Addition); Func<int, int, string> add2 = new Func<int,
int, string>(Metho dCollections.DisplayAddition);
Func<string, string, string> completeName = new Func<string, s tring,
string>(MethodCollections.SHowCompleteName);
Func<int> random = new Func<int>(MethodCollections.ShowNumber);
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 MyDelegate(string str);
The preceding code defines a delegate named MyDelegate and an event named delg,
which invokes the delegate when it is raised.
To declare an event inside a class, first a Delegate type for the Event must be declared
like below:
public delegate void MyEventHandler(object sender, EventArgs e);
Defining an event is a two-step process.
• First, you need to define a delegate type that will hold the list of methods to be
called when the event is fired.
• Next, you declare an event using the event keyword.
To illustrate the event, we are creating a console application. In this iteration, we will
define an event to add that is associated to a single delegate DelEventHandler.
using System;
public delegate void DelEventHandler();
class Program
{
public static event DelEventHandler add;
static void USA()
{
Console.WriteLine("USA");
}
static void India()
{
Console.WriteLine("India");
}
static void England()
{
Console.WriteLine("England");
}
Console.ReadLine();
}
//custom delegate
public delegate void DelEventHandler();
class Program :Form
{
//custom event
public event DelEventHandler add;
public Program()
{
// design a button over form
Button btn = new Button();
btn.Parent = this; btn.Text
= "Hit Me";
btn.Location = new Point(100,100);
Console.ReadLine();
}
}
Can we use Events without Delegate?
No, Events use Delegates internally. Events are encapsulation over Delegates. There is
already defined Delegate "EventHandler" that can be used like below:
public event EventHandler MyEvents; So,
it also used Delegate Internally.
Anonymous Method in C#
An anonymous method is a method which doesn’t contain any name which is
introduced in C# 2.0. It is useful when the user wants to create an inline method and also
wants to pass parameter in the anonymous method like other methods.
An Anonymous method is defined using the delegate keyword and the user can assign
this method to a variable of the delegate type.
delegate(parameter_list){
// Code..
};
Example: using
System;
class
GFG {
public delegate void petanim(string pet);
// Main method
static public void Main()
{
Output:
My favorite pet is: Dog
Lambda Expressions
Lambda expressions in C# are used like anonymous functions, with the difference that in
Lambda expressions you don’t need to specify the type of the value that you input thus
making it more flexible to use.
The ‘=>’ is the lambda operator which is used in all lambda expressions. The Lambda
expression is divided into two parts, the left side is the input and the right is the
expression.
class LambdaTest
{
static int test1() => 5;
static int test2(int x) => x + 10;
Output:
Result is: 15
Throwing Exceptions
Exceptions can be thrown either by the runtime or in user code. In this example, Display
throws a System.ArgumentNullException:
Re-throwing an exception
You can capture and re-throw an exception as follows:
System.ArgumentException
Thrown when a function is called with a bogus argument. This generally indi‐ cates a
program bug.
System.ArgumentNullException
Subclass of ArgumentException that’s thrown when a function argument is
(unexpectedly) null.
System.ArgumentOutOfRangeException
Subclass of ArgumentException that’s thrown when a (usually numeric) argu‐ ment is too
big or too small. For example, this is thrown when passing a nega‐ tive number into a
function that accepts only positive values.
System.InvalidOperationException
Thrown when the state of an object is unsuitable for a method to successfully execute,
regardless of any particular argument values. Examples include read‐ ing an unopened file
or getting the next element from an enumerator where the underlying list has been
modified partway through the iteration.
System.NotSupportedException
Thrown to indicate that a particular functionality is not supported. A good example is
calling the Add method on a collection for which IsReadOnly returns true.
System.NotImplementedException
Thrown to indicate that a function has not yet been implemented.
System.ObjectDisposedException
Thrown when the object upon which the function is called has been disposed.
Introduction to LINQ
LINQ (Language Integrated Query) is uniform query syntax in C# to retrieve data from
different sources and formats. It is integrated in C#, 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# 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.
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'.
LINQ Method
The following is a sample LINQ method syntax query that returns a collection of strings
which contains a word "Tutorials". We use lambda expression for this purpose.
}
}
Output
:
2 4 6
}
Console.Read();
}
}
Output:
Rex
Sean
Stacy
Output:
Dog Rex is 4 years old.
Dog Stacy is 3 years old.
Dog Sean is 0 years old.
LINQ Operators
Classification LINQ Operators
Filtering Where, OfType
Sorting OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse
Grouping GroupBy, ToLookup
Join GroupJoin, Join
Projection Select, SelectMany
Aggregation Aggregate, Average, Count, LongCount, Max, Min, Sum
Quantifiers All, Any, Contains
Elements ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last,
LastOrDefault, Single, SingleOrDefault
Set Distinct, Except, Intersect, Union
Partitioning Skip, SkipWhile, Take, TakeWhile
Concatenation Concat
Equality Equals,SequenceEqual
Generation DefaultEmpty, Empty, Range, Repeat
Conversion AsEnumerable, AsQueryable, Cast, ToArray, ToDictionary, ToList
//Multiple Condition
var result = names.Where(s=>s.Contains("Ram") ||
s.Contains("Gita"));
foreach (string val in result)
{
Console.WriteLine(val);
}
Console.ReadLine();
}
}
}
Output
: Ram
Gita
Console.WriteLine(res.sid+"\t"+res.name+"\t"+res.address);
}
Console.ReadLine();
}
}
Output:
Sid Name Address
1 Ram Btm
//using union
var result = names.Union(address);
foreach (var res in result) {
Console.WriteLine(res);
}
Console.ReadLine();
} }
Using aggregate functions – Example 1
class LinqTest {
static void Main(string[] args)
{
List<int> marks = new List<int>() { 10,30,50,20,5};
int max = marks.Max(); int min = marks.Min();
int sum = marks.Sum(); int total = marks.Count();
Console.WriteLine("Maximum marks="+max);
Console.WriteLine("Minimum marks=" + min);
Console.WriteLine("Sum of marks=" + sum);
Console.WriteLine("Total Count=" + total);
Console.ReadLine();
}
}
class Student
{
public int sid { get; set; }
public string name { get; set; }
public string address { get; set; }
Console.ReadLine();
}
}
Output
Max Id=4
Total Students=4
Using Order By
class Student
{
public int sid { get; set; }
public string name { get; set; }
public string address { get; set; }
Console.WriteLine(res.sid+"\t"+res.name+"\t"
+ res.address);
}
}
Console.ReadLine();
}
}
Output:
Group Key: Btm
Sid Name Address
1 Ram Btm
3 Shyam Btm
Group Key: Ktm
Sid Name Address
2 Hari Ktm
4 Gita Ktm
ADO : ActiveX Data Objects and ADO.Net are two different ways to access database in
Microsoft.
ADO ADO.Net
ADO is base on COM : Component Object ADO.Net is based on CLR : Common
Modelling based. Language Runtime based.
ADO stores data in binary format. ADO.Net stores data in XML format i.e.
parsing of data.
ADO can’t be integrated with XML because ADO.Net can be integrated with XML as
ADO have limited access of XML. having robust support of XML.
ADO is connection oriented means it requires ADO.Net is disconnected, does not need
continuous active connection. continuous connection.
ADO gives rows as single table view, it scans ADO.Net gives rows as collections so you can
sequentially the rows using MoveNext access any record and also can go through a
method. table via loop.
In ADO, You can create only Client side cursor. In ADO.Net, You can create both Client &
Server side cursor.
Using a single connection instance, ADO can Using a single connection instance, ADO.Net
not handle multiple transactions. can handle multiple transactions.
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object
is used to read the data from database and bind that data to dataset. Dataadapter is a
disconnected oriented architecture.
//Example
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet(); da.Fill(ds);
DataAdapter
- Lets you close the connection as soon it's done loading data, and may even close it
for you automatically
- All of the results are available in memory
- You can iterate over it as many times as you need, or even look up a specific
record by index
- Has some built-in faculties for updating back to the database.
DataTable represents a single table in the database. It has rows and columns. There is no
much difference between dataset and datatable, dataset is simply the collection of
datatables.
//Example
DataTable dt = new DataTable();
da.Fill(dt);
3) Data reader is an object through which you can read a sequential stream of data.
it's a forward only data wherein you cannot go back to read previous data. data set and
data adapter object help us to work in disconnected mode. data set is an in cache
memory representation of tables. the data is filled from the data source to the data set
thro' the data adapter. once the table in the dataset is modified, the changes are
broadcast to the database back throw; the data adapter.
Connect C# to MySQL
• First make sure you have downloaded and installed the MySQL Connector/NET
from the MySQL official website.
• Add reference MySql.Data in your project.
using MySql.Data.MySqlClient;
string constr = "SERVER=localhost; DATABASE=dbtest; UID=root;
PASSWORD=;";
MySqlConnection conn = new MySqlConnection(constr);
Console.ReadKey();
}
}
}
case 2:
Console.WriteLine("Enter id to be updated");
id = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Ënter Name of Student: ");
nm = Console.ReadLine();
Console.WriteLine("Ënter Address of Student: ");
add = Console.ReadLine();
sql = "UPDATE tblStudent SET name='"+nm+"',
address='"+add+"' WHERE sid="+id;
obj.InsertUpdateDelete(sql);
break;
case
3:
Console.WriteLine("Enter id to be deleted");
id = Convert.ToInt32(Console.ReadLine()); sql
= "DELETE FROM tblStudent WHERE sid="+id;
obj.InsertUpdateDelete(sql); break;
case 4: sql
= "SELECT * FROM tblStudent";
obj.SelectRecords(sql); break;
default:
Console.WriteLine("Wrong Choice");
break;
}
goto x; }
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine("Connection Failed !");
}
Console.ReadKey();
}
}
}
Basic Controls:
The following table lists some of the commonly used controls:
S.N. Widget & Description
1 Forms
The container for all the controls that make up the user interface.
2 TextBox
3 Label
4 Button
5 ListBox
6 ComboBox
7 RadioButton
It enables the user to select a single option from a group of choices when paired
with other RadioButton controls.
8 CheckBox
9 PictureBox
10 ProgressBar
11 ScrollBar
It represents a Windows control that allows the user to select a date and a time
and to display the date and time with a specified format.
13 TreeView
14 ListView
It represents a Windows list view control, which displays a collection of items that
can be displayed using one of four different views.
Label controls provide an easy way to display text which can be changed from one
execution of a page to the next. If you want to display text that does not change, you use
the literal text.
<asp:TextBox ID="txtstate" runat="server" ></asp:TextBox>
Check Boxes and Radio Buttons
A check box displays a single option that the user can either check or uncheck and radio
buttons present a group of options from which the user can select just one option.
To create a group of radio buttons, you specify the same name for the GroupName
attribute of each radio button in the group. If more than one group is required in a single
form, then specify a different group name for each group.
If you want check box or radio button to be selected when the form is initially displayed,
set its Checked attribute to true. If the Checked attribute is set to true for multiple radio
buttons in a group, then only the last one is considered as true.
HyperLink Control
The HyperLink control is like the HTML <a> element.
<asp:HyperLink ID="HyperLink1" runat="server">
HyperLink
</asp:HyperLink>
Image Control
The image control is used for displaying images on the web page, or some alternative
text, if the image is not available.
<asp:Image ID="Image1" ImageUrl=”url” runat="server">
EventHandling.aspx
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="First Number">
</asp:Label>
<asp:TextBox ID="txtFirst" runat="server"></asp:TextBox>
<br/><br/>
<asp:Label ID="Label2" runat="server" Text="First Number">
</asp:Label>
<asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>
<br/><br/>
<asp:Label ID="lblResult" runat="server" Text="Result:">
</asp:Label> <br/><br/>
<asp:Button ID="btnSubmit" runat="server" Text="Get Result"
onClick="btnSubmit_Click"/>
</div>
</form>
Dropdown.aspx
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Program">
</asp:Label>
<asp:DropDownList ID="dropProgram" runat="server">
</asp:DropDownList>
<br/><br/>
<asp:Label ID="lblSelected" runat="server" Text="Selected:">
</asp:Label>
<br/><br/>
<asp:Button ID="btnSelect" runat="server" Text="Select"
OnClick="btnSelect_Click" />
</div>
</form>
Dropdown.cs
private void LoadData()
{
List<ListItem> mylist=new List<ListItem>();
mylist.Add(new ListItem("BCA","1")); mylist.Add(new
ListItem("BBA","2")); mylist.Add(new
ListItem("MCA","3")); mylist.Add(new
ListItem("MBA","4"));
dropProgram.Items.AddRange(mylist.ToArray());
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string text = dropProgram.SelectedItem.ToString();
string value = dropProgram.SelectedValue;
lblSelected.Text = "Selected Text: " + text + " Selected
Value: " + value;
}
example.aspx
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Gender"></asp:Label>
<asp:RadioButton ID="radioMale" Text="Male" GroupName="gender"
runat="server" />
<asp:RadioButton ID="radioFemale" Text="Female"
GroupName="gender" runat="server" />
<br/><br/>
<asp:Label ID="lblSelected" runat="server" Text="Selected
Radio:"> </asp:Label>
<br/><br/>
<asp:Button ID="btnSelect" runat="server" Text="Select"
OnClick="btnSelect_Click" />
</div>
</form>
example.cs protected void btnSelect_Click(object sender,
EventArgs e)
{
if (radioMale.Checked)
lblSelected.Text = "Male Selected";
else
lblSelected.Text = "Female Selected";
}
Example – 5 Using Check box
example.aspx
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Gender"></asp:Label>
<asp:CheckBox ID="chkMale" Text="Male" GroupName="gender"
runat="server" />
<asp:CheckBox ID="chkFemale" Text="Female"
GroupName="gender" runat="server" />
<br/><br/>
<asp:Label ID="lblSelected" runat="server" Text="Selected
Radio:"> </asp:Label>
<br/><br/>
<asp:Button ID="btnSelect" runat="server" Text="Select"
OnClick="btnSelect_Click" />
</div>
</form>
example.cs protected void btnSelect_Click(object sender,
EventArgs e)
{
if (chkMale.Checked)
lblSelected.Text = "Male Selected";
else
lblSelected.Text = "Female Selected";
}