C# UNIT 3
C# UNIT 3
INTERFACE
It is like abstract class because all the methods which are declared inside the interface are abstract methods.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve fully abstraction because
Its implementation must be provided by class or struct. The class or struct which implements the interface, must provide
It is mainly used to assign the names or string values to integral constants, that make a program easy to read and maintain.
For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade,
In C#, Clone() is a String method. It is used to clone the string object, which returns another copy of that data.
C# program to illustrate
In other words, it returns a reference to this instance of String. // Clone() method
using System;
The return value will be only another view of the same data. class Geeks {
Definition
Namespace: System.Collections
Assembly:System.Runtime.dll
Performs a case-sensitive comparison of two objects of the same type and returns a value indicating whether
one is less than, equal to, or greater than the other.
SYNTAX
public int Compare (object? a, object? b);
Parameters
A Object
The first object to compare.
B Object
The second object to compare.
Returns Int32
A signed integer that indicates the relative values of a and b, as shown in the following table.
VALUE MEANING
Implements
Compare(Object, Object)
Exceptions
ArgumentException
Neither a nor b implements the IComparable interface.
-or-
a and b are of different types and neither one can handle
comparisons with the other.
Indexers
An indexer allows an instance of a class or struct to be indexed as an array.
If the user will define an indexer for a class, then the class will behave like a virtual array.
Array access operator i.e ([ ]) is used to access the instance of the class which uses an indexer.
Syntax:
[access_modifier] [return_type] this [argument_list] access_modifier: It can be public, private,
protected or internal.
{
return_type: It can be any valid C# type.
get this: It is the keyword which points to the object of
the current class.
{
argument_list: This specifies the parameter list of
// get block code the indexer.
get{ } and set { }: These are the accessors.
}
set
{
// set block code
}
}
Implementing Indexers
1.Multiple Index Parameters: Indexers can have multiple parameters, allowing for more complex indexing scenarios. You
can define an indexer with multiple parameters to access elements based on different criteria.
2.Indexer Overloading: Similar to methods, indexers can be overloaded in C#. This means you can define multiple
indexers with different parameter types or counts, providing different ways to access elements in the class or struct.
3.Read-Only Indexers: By omitting the set accessor in the indexer declaration, you can create read-only indexers. This
restricts the ability to modify elements through the indexer, allowing only the retrieval of values.
4.Implicit vs. Explicit Interface Implementation: Indexers can be implemented implicitly or explicitly when defined as
part of an interface. Implicit implementation is used when the indexer is defined within the class itself, while explicit
implementation is used when the indexer is implemented explicitly to resolve any naming conflicts.
5.Indexers in Collections: Indexers are commonly used in collection classes, such as dictionaries, lists, and arrays. They
provide a convenient way to access and manipulate elements within these collections based on an index or key.
6.Indexers in Custom Classes: Indexers can be implemented in custom classes to provide customized access to class
members based on an index. This allows for more intuitive and expressive interaction with instances of the class.
Important Points About Indexers:
•There are two types of Indexers i.e. One Dimensional Indexer & MultiDimensional Indexersperforming
•A set accessor will always assign the value while the get accessor will return the value.
•To define the value being assigned by the set indexer, ” value” keyword is used.
•Indexers are also known as the Smart Arrays or Parameterized Property in C#.
In C#, delegate is a reference to the method. It works like function pointer in C and C++. But it is objected-oriented,
For static method, delegate encapsulates method only. But for instance method, it encapsulates method and instance
both.
Internally a delegate declaration defines a class which is the derived class of System.Delegate.
The "-" operator can be used to remove a component delegate from a composed delegate.
Using this property of delegates you can create an invocation list of methods that will be called when a delegate is
invoked.
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated
notifications.
The events are declared and raised in a class and associated with the event handlers using delegates within the same class
Some other class that accepts this event is called the subscriber class.
public EventProgram() {
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username) {
return "Welcome " + username;
}
Multithreading
If your application involves complicated and time consuming operations, then it is often helpful to set different
However, this way the application can perform one job at a time.
To make it execute more than one task at a time, it could be divided into smaller threads.
Thread Life Cycle
Thread class is created and ends when the thread is terminated or completes execution.
The Unstarted State − It is the situation when the instance of the thread is created but the Start method is not called.
The Ready State − It is the situation when the thread is ready to run and waiting CPU cycle.
The Dead State − It is the situation when the thread completes execution or is aborted.
The Main Thread using System;
using System.Threading;
In C#, the System.Threading.Thread class is used for working with threads.
namespace
MultithreadingApplication {
It allows creating and accessing individual threads in a multithreaded application. class MainThreadProgram {
static void Main(string[] args)
The first thread to be executed in a process is called the main thread. {
Thread th =
Thread.CurrentThread;
When a C# program starts execution, the main thread is automatically created. th.Name = "MainThread";
The threads created using the Thread class are called the child threads of the main Console.WriteLine("This is
{0}", th.Name);
Console.ReadKey();
thread. }
}
You can access a thread using the CurrentThread property of the Thread class. }
Properties and Methods of the Thread Class
The following table shows some most commonly used properties of the Thread class −
The extended Thread class then calls the Start() method to begin the child thread execution.
using System;
using System.Threading;
namespace MultithreadingApplication {
class ThreadCreationProgram {
public static void CallToChildThread() {
Console.WriteLine("Child thread starts");
}
static void Main(string[] args) {
ThreadStart childref = new
ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
Managing Threads
The following example demonstrates the use of the sleep() method for making a thread pause for a specific period of
time.
static void Main(string[] args) {
using System; ThreadStart childref = new
using System.Threading; ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child
namespace MultithreadingApplication { thread");
class ThreadCreationProgram {
public static void CallToChildThread() { Thread childThread = new Thread(childref);
Console.WriteLine("Child thread starts"); childThread.Start();
Console.ReadKey();
// the thread is paused for 5000 milliseconds }
int sleepfor = 5000; }
}
Console.WriteLine("Child Thread Paused for {0}
seconds", sleepfor / 1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
Destroying Threads
This exception cannot be caught, the control is sent to the finally block, Console.WriteLine("Child Thread
Completed");
using System; } catch (ThreadAbortException e) {
using System.Threading; Console.WriteLine("Thread Abort
Exception");
namespace MultithreadingApplication { } finally {
class ThreadCreationProgram { Console.WriteLine("Couldn't catch
public static void CallToChildThread() { the Thread Exception");
try { }
Console.WriteLine("Child thread starts"); }
static void Main(string[] args) {
// do some work, like counting to 10 ThreadStart childref = new
for (int counter = 0; counter <= 10; counter++) { ThreadStart(CallToChildThread);
Thread.Sleep(500); Console.WriteLine("In Main: Creating
Console.WriteLine(counter); the Child thread");
}
Thread childThread = new Thread(childref);
childThread.Start(); When the above code is compiled and executed, it
produces the following result −
//stop the main thread for some time
Thread.Sleep(2000); In Main: Creating the Child thread
Child thread starts
//now abort the child 0
Console.WriteLine("In Main: Aborting the Child 1
thread"); 2
In Main: Aborting the Child thread
childThread.Abort(); Thread Abort Exception
Console.ReadKey(); Couldn't catch the Thread Exception
}
}
}
C# Windows Forms Applications
Windows Forms is a Graphical User Interface(GUI) class library which is bundled in .Net Framework.
Its main purpose is to provide an easier interface to develop the applications for desktop, tablet, PCs.
The applications which are developed by using Windows Forms or WinForms are known as the Windows Forms
WinForms can be used only to develop the Windows Forms Applications not web applications.
WinForms applications can contain the different type of controls like labels, list boxes, tooltip etc.
Creating a Windows Forms Application Using Visual Studio 2017
First, open the Visual Studio then Go to File -> New -> Project to create a new project and then select the language
as Visual C# from the left menu.
Click on Windows Forms App(.NET Framework) in the middle of current window. After that give the project name
and Click OK.
Here the solution is like a container which contains the projects and files that may be required by the program.
After that following window will display which will be divided into three parts as follows:
Editor Window or Main Window: Here, you will work with forms and code editing. You can notice the layout of form which
is now blank. You will double click the form then it will open the code for that.
Solution Explorer Window: It is used to navigate between all items in solution. For example, if you will select a file form this
Properties Window: This window is used to change the different properties of the selected item in the Solution Explorer.
Also, you can change the properties of components or controls that you will add to the forms.
Now to add the controls to your WinForms application go to Toolbox tab present in the extreme left side of Visual
Studio. Here, you can see a list of controls.
To access the most commonly used controls go to Common Controls present in Toolbox tab.
To run the program you can use an F5 key or Play button present in the toolbar of Visual Studio.
To stop the program you can use pause button present in the ToolBar.
You can also run the program by going to Debug->Start Debugging menu in the menubar.
The Windows Forms framework provides a rich set of controls that developers can use to build applications
with. These controls are designed to provide a consistent and familiar user interface for Windows users.
Developers can customize the appearance and behavior of these controls by setting various properties and
handling events.
To create a Windows Forms application in C#, you can use Microsoft Visual Studio, which is an integrated
development environment (IDE) that provides a visual designer to create and layout the user interface elements.
The visual designer is a drag-and-drop interface for building your UI, and you can easily configure each
code for the application’s logic. Developers can handle events and perform tasks such as data validation, data
Windows Forms applications are versatile and can be used to create various types of applications such as data entry,
Windows Forms is that part of the .NET Framework that supports building traditional GUI applications on the
Windows platform.
It provides a large set of classes that make it easy to create sophisticated user interfaces.
Step 3: After drag and drop you will go to the properties of the
TextBox control to modify the TextBox design according to your
requirement.
2. Run-Time: It is a little bit trickier than the above method. In // Set the foreground color of the textbox
this method, you can create your own textbox using the Mytextbox.ForeColor =
TextBox class. Color.DarkOliveGreen;
Step 1 : Create a textbox using the TextBox() constructor // Set the size of the textbox
provided by the TextBox class. Mytextbox.AutoSize = true;
// Creating textbox
TextBox Mytextbox = new TextBox(); // Set the name of the textbox
Mytextbox.Name = "text_box1";
Step 2 : After creating TextBox, set the properties of the
TextBox provided by the TextBox class. Step 3 : And last add this textbox control to
form using Add() method.
// Set location of the textbox
Mytextbox.Location = new Point(187, 51); // Add this textbox to form
this.Controls.Add(Mytextbox);
// Set background color of the textbox
Mytextbox.BackColor = Color.LightGray;
CheckBox in C#
The CheckBox control is the part of windows form which is used to take input from the user.
Or in other words, CheckBox control allows us to select single or multiple elements from the given list or it can
provide us options like yes or no, true or false, etc.
It can be displayed as an image or text or both.
The CheckBox is a class and defined under System.Windows.Forms namespace.
In Windows form, you can create CheckBox in two different ways:
Step 3: After drag and drop you will go to the properties of the
CheckBox control to modify the CheckBox design according to
your requirement.
Output:
Run-Time: It is a little bit trickier than the above method. In
this method, you can create your own checkbox
programmatically using the CheckBox class. // Set font of the checkbox
Mycheckbox.Font = new Font("Bradley Hand ITC",
Step 1: Create a checkbox using the CheckBox() constructor 12);
provided by the CheckBox class. Step 3: And last add this checkbox control to form
// Creating checkbox using Add() method.
CheckBox Mycheckbox = new CheckBox(); // Add this checkbox to form
this.Controls.Add(Mycheckbox);
Step 2: After creating CheckBox, set the properties of the
CheckBox provided by the CheckBox class.
// Set height of the checkbox
Mycheckbox.Height = 50;
In Windows Forms, RadioButton control is used to select a single option among the group of the options.
For example, select your gender from the given list, so you will choose only one option among three options like
Male or Female or Transgender.
In C#, RadioButton is a class and it is defined under System.Windows.Forms namespace. In RadioButton, you are
allowed to display text, image, or both and when you select one radio button in a group other radio buttons
automatically clear.
You can create RadioButton in two different ways:
1. Design-Time: It is the easiest way to create a RadioButton control as shown in the following steps:
Step 1: Create a windows form as shown in the below image:
Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the RadioButton control from the ToolBox and
drop it on the windows form.
You are allowed to place a RadioButton control anywhere on
the windows form according to your need
Step 3: After drag and drop you will go to the properties of the
RadioButton control to modify RadioButton control according
to your requirement
2. Run-Time: It is a little bit trickier than the above method. // Add text in RadioButton
In this method, you can create a RadioButton programmatically r1.Text = "Intern";
with the help of the RadioButton class.
// Set the location of the RadioButton
The following steps show how to create a RadioButton r1.Location = new Point(286, 40);
dynamically:
// Set Font property
Step 1: Create a radio button using the RadioButton() r1.Font = new Font("Berlin Sans FB", 12);
constructor is provided by the RadioButton class.
// Creating radio button Step 3: And last add this RadioButton control to the
RadioButton r1 = new RadioButton(); form using Add() method.
// Add this radio button to the form
Step 2: After creating RadioButton, set the properties of the this.Controls.Add(r1);
RadioButton provided by the RadioButton class.
// Set the AutoSize property
r1.AutoSize = true;
GroupBox Class
In Windows form, GroupBox is a container which contains multiple controls on it and the controls are related to
each other.
Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a
GroupBox is used to categorize the related controls in a group.
The GroupBox class is used to represent the windows group box and also provide different types of properties,
methods, and events.
It is defined under System.Windows.Forms namespace.
The main use of a group box is to hold a logical group of RadioButton controls.
In C# you can create a GroupBox in the windows form by using two different ways:
Step 3: After drag and drop you will go to the properties of the
GroupBox to modify GroupBox according to your requirement.
Run-Time: It is a little bit trickier than the above method. // Setting the size of the GroupBox
In this method, you can create a GroupBox programmatically box.Size = new Size(329, 94);
with the help of syntax provided by the GroupBox class.
// Setting text the GroupBox
The following steps show how to set the create GroupBox box.Text = "Select Gender";
dynamically:
// Setting the name of the GroupBox
Step 1: Create a GroupBox using the GroupBox() constructor is box.Name = "MyGroupbox";
provided by the GroupBox class.
// Creating a GroupBox Step 3: And last add this GroupBox control to the
GroupBox box = new GroupBox(); form and also add other controls on the GroupBox
using the following statements:
Step 2: After creating GroupBox, set the property of the
GroupBox provided by the GroupBox class. // Adding groupbox in the form
// Setting the location of the GroupBox this.Controls.Add(box);
box.Location = new Point(179, 145);
and
more elements and the elements are generally displayed in multiple columns.
The ListBox class is used to represent the windows list box and also provide different types of properties, methods,
and events.
The ListBox class contains three different types of collection classes, i.e.
ListBox.ObjectCollection: This class holds all the elements contained in the ListBox control.
ListBox.SelectedObjectCollection: This class holds a collection of the selected items which is a subset of the items
ListBox.SelectedIndexCollection: This class holds a collection of the selected indexes, which is a subset of the
indexes of the ListBox.ObjectCollection and these indexes specify elements that are selected.
In C# you can create a ListBox in the windows form by using
two different ways:
Step 2: Next, drag and drop the ListBox control from the
toolbox to the form.
Step 3: After drag and drop you will go to the properties of the
ListBox control to modify ListBox according to your
requirement.
2. Run-Time: It is a little bit trickier than the above method.
In this method, you can create a ListBox control Step 3: And last add this ListBox control to
programmatically with the help of syntax provided by the the form using the following statement:
ListBox class. // Adding ListBox control
The following steps show how to set the create ListBox // to the form
dynamically:
In Windows Forms, ComboBox provides two different features in a single control, it means ComboBox works as
both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are
1. Design-Time: It is the easiest method to create a ComboBox control using the following steps:
Step 3: After drag and drop you will go to the properties of the
ComboBox control to set the properties of the ComboBox
according to your need.
Run-Time: It is a little bit trickier than the above method. In this // Add items in the ComboBox
method, you can set create your own ComboBox control using mybox.Items.Add("C#");
the ComboBox class. Steps to create a dynamic ComboBox: mybox.Items.Add("Java");
mybox.Items.Add("Scala");
Step 1: Create a combobox using the ComboBox() constructor mybox.Items.Add("C");
is provided by the ComboBox class. mybox.Items.Add("C++");
// Creating combobox using ComboBox class
ComboBox mybox = new ComboBox(); Step 3: And last add this ComboBox control to
form using Add() method.
// Add this ComboBox to the form
Step 2: After creating ComboBox, set the properties of the this.Controls.Add(mybox);
ComboBox provided by the ComboBox class.
// Set the location of the ComboBox
mybox.Location = new Point(327, 77);
TrackBar control provides scrolling with a little different interface than a scrollbar.
Creating a TrackBar
We can create a TrackBar control using a Forms designer at design-time or using the TrackBar class in code at run-time.
To create a TrackBar control at design-time, you simply drag and drop a TrackBar control from Toolbox to a Form in
Visual Studio.
After you drag and drop a TrackBar on a Form, the TrackBar looks like Figure 1.
Once a TrackBar is on the Form, you can move it around and resize it using mouse and set its properties and events
First step to create a dynamic TrackBar is to create an instance of TrackBar class. The following code snippet creates a
TrackBar control object.
In the next step, you may set properties of a TrackBar control. The following code snippet sets the height and width
properties of a TrackBar.
tbar.Height = 40;
tbar.Width = 300;
Calendar Control in C#
A DateTime represents an instant in time. The string representation of a datetime is culture-specific and
depends both on the conventions used for displaying date and time and its calendar. A calendar is a system of
organizing datetime units.
CultureInfo provides information about a specific culture. The information includes the names for the culture,
the writing system, the calendar used, the sort order of strings, and formatting for dates and numbers.
GregorianCalendar is the most popular calendar and is used as the default for the culture-independent option.
Each CultureInfo supports a set of calendars. The Calendar returns the default calendar for the culture. The
OptionalCalendars gives an array containing all the calendars supported by the culture.
Display mode=Month
<controls:Calendar Name="Calender1" HorizontalAlignment="Left" Height="250" Width="250"
DisplayMode="Month" VerticalAlignment="Top"></controls:Calendar>
Spin Boxes
A spin box—sometimes called a spinner control—is a collective term for the combination of a
text box with an up-down control.
Users can click arrow buttons (the up-down control) or press the UP ARROW or DOWN
ARROW key to change the value in the text box. The value ascends or descends
incrementally.
Panel In C#
Creating a Panel
We can create a Panel Control using the Forms designer at design-time or using the Panel
class in code at run-time.
Design-time
To create a Panel Control at design-time, you can drag and drop a Panel Control from the
Toolbox to a Form in Visual Studio. After you dragging and dropping a Panel Control to the
Form.
Once a Panel is on the form, you can move it around and resize it using the mouse and set
its properties and events.
Run-time
Creating a Panel Control at run-time is merely a work of creating an instance of the Panel class, setting
its properties and adding the Panel to the form controls.
The first step to create a dynamic Panel is to create an instance of the Panel class. The following code
snippet creates a Panel Control object.
The following code snippet sets the location, size and Name properties of a Panel.
After you place a Panel Control on a form, the next step is to set its properties.
The easiest way to set properties is from the Properties Window. You can open the Properties window by
pressing F4 or right-clicking on a control and selecting the Properties menu item.
Adding Controls to a Panel
You can add controls to a Panel by dragging and dropping a control to the Panel. We can add controls
to a Panel at run-time by using its Add method. The following code snippet creates a Panel, creates a
TextBox and a CheckBox and adds these two controls to a Panel.
Creating a Tooltip
Tooltip class represents a tooltip control. Once a Tooltip object is created, we need to call SetToolTip method
and pass a control and text. The following code snippet creates a Tooltip and attaches to a Button control using
SetToolTip method.
ToolTip toolTip1 = newToolTip();
toolTip1.ShowAlways = true;
toolTip1.SetToolTip(button1, "Click me to execute.");
Tooltip Properties
Active - A tooltip is currently active.
AutomaticDelay - Automatic delay for the tooltip.
AutoPopDelay - The period of time the ToolTip remains visible if the pointer is stationary on a control with
specified ToolTip text.
InitialDelay - Gets or sets the time that passes before the ToolTip appears.
IsBaloon - Gets or sets a value indicating whether the ToolTip should use a balloon window.
ReshowDelay - Gets or sets the length of time that must transpire before subsequent ToolTip windows appear
as the pointer moves from one control to another.
ShowAlways - Displays if tooltip is displayed even if the parent control is not active.
ToolTipIcon - Icon of tooltip window.
ToolTipTitle - Title of tooltip window.
UseAnimation - Represents whether an animation effect should be used when displaying the tooltip.
UseFading - Represents whether a fade effect should be used when displaying the tooltip
The following code snippet sets some of these properties.
ToolTip buttonToolTip = newToolTip();
buttonToolTip.ToolTipTitle = "Button Tooltip";
buttonToolTip.UseFading = true;
buttonToolTip.UseAnimation = true;
buttonToolTip.IsBalloon = true;
buttonToolTip.ShowAlways = true;
buttonToolTip.AutoPopDelay = 5000;
buttonToolTip.InitialDelay = 1000;
buttonToolTip.ReshowDelay = 500;
buttonToolTip.SetToolTip(button1, "Click me to execute.");
Error Provider in a C# Windows Forms Application
In this example I will use a Display Warning icon, Wrong icon (when an incorrect expression is entereded) or a
Tick icon depending upon the data entered in the text box so that the user can determine that data entered is
correct or incorrect.
Sometimes, in a graphical user interface, a window is used to communicate with the user or establish a dialog
between the user and the application. This additional window is called a dialog box. It may communicate
information to the user; prompt the user for a response or both.
The simplest type of dialog box is the warning which displays a message and may require the user to
acknowledge that the message has been read, usually by clicking “OK” or a decision as to whether or not an
action should continue by clicking “OK” or “Cancel”.
Some dialog boxes are standard like the warning message or error message. Save the file and enter the
password. These are called standard dialog boxes.
A dialog box can also be customized. Such a dialog box is called a custom dialog box.
Dialog boxes are special forms that are non-resizable. They are also used to display the messages to the user. The
messages can be error messages, confirmation of the password, confirmation for the deletion of a particular
record, Find-Replace utility of the word etc. There are standard dialog boxes to open and save a file, select a folder,
print the documents, set the font or color for the text, etc.
MessageBox class is used to display messages to the user. The show() method is used to display a message box
with the specified text, caption, buttons, and icon. There are other overloads also available.