SlideShare a Scribd company logo
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
1
Unit – 01
Introduction to .Net Technologies
Introduction to HTML
➢ HTML stands for Hyper Text Markup Language.
➢ HTML was invented by Tim Berners-Lee
➢ HTML is the standard markup language for creating Web pages.
➢ HTML describes the structure of a Web page
➢ HTML consists of a series of elements
➢ HTML elements tell the browser how to display the content
➢ HTML elements label pieces of content such as "this is a heading", "this isa paragraph", "this is a
link", etc.
➢ HTML5 described as a new version of HTML.
➢ HTML5 was the successor to previous HTML versions.
➢ HTML is Not Case Sensitive.
HTML History
Since the early days of the World Wide Web, there have been many versions of HTML:
Year Version
1989 Tim Berners-Lee invented www
1991 Tim Berners-Lee invented HTML
1993 Dave Raggett drafted HTML+
1995 HTML Working Group defined HTML 2.0
1997 HTML 3.2
1999 HTML 4.01
2000 XHTML 1.0
2008 WHATWG HTML5 First Public Draft
2012 WHATWG HTML5 Living Standard
2014 HTML5
2016 HTML 5.1
2017 HTML5.1 2nd Edition
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
2
Editors:
➢ Web pages can be created and modified by using professional HTML editors.
➢ For learning HTML, we need to use a simple text editor like Notepad (PC) or TextEdit (Mac).
HTML Element
➢ An HTML element is defined by a start tag, some content, and an end tag:
o <tagname> Content goes here... </tagname>
➢ The HTML element is everything from the start tag to the end tag:
o <h1>My First Heading</h1>
o <p>My first paragraph.</p>
HTML Attributes
➢ All HTML elements can have attributes.
➢ Attributes provide additional information about elements.
➢ Attributes are always specified in the start tag.
➢ Attributes usually come in name/value pairs like: name="value".
HTML Basic Tags
HTML Headings: HTML headings are defined with the <h1> to <h6> tags.
Ex:
o <h1>This is heading 1</h1>
o <h2>This is heading 2</h2>
o <h3>This is heading 3</h3>
HTML Paragraphs: HTML paragraphs are defined with the <p> tag:
Ex: <p>This is a paragraph.</p>
HTML Links: HTML links are defined with the <a> tag, The “href” attribute specifies the URL ofthe page
the link goes to:
Ex: <a href="https://www.bbc.edu.in">This is a link</a>
HTML Images:
➢ HTML images are defined with the <img> tag.
➢ The source file (src), alternative text (alt), width, and height are provided asattributes:
Ex: <img src=" c:picturesa1.jpg” alt=" Picture notfound” width="104" height="142">
Marquee Tags:
➢ The Marquee HTML tag is a non-standard HTML element, which is used toscroll a image or text
horizontally or vertically.
➢ In simple words, we can say that it scrolls the image or text up, down, left or rightautomatically.
➢ Marquee tag was first introduced in early versions of Microsoft's Internet Explorer.
Ex: <marquee width="100%" direction="right">
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
3
This is an example of a right direction marquee...
</marquee>
The style Attribute
The style attribute is used to add styles to an element, such as color, font, size,and more.
Ex: <p style="color:red;">This is a red paragraph.</p>
The lang Attribute:
➢ You should always include the lang attribute inside the <html> tag, to declare thelanguage of the
Web page.
➢ This is meant to assist search engines and browsers.
Ex: <html lang="en">
How to View HTML Source
Right-click in an HTML page and select "View Page Source" (in Chrome) or "View Source" (in Edge),
or similar in other browsers. This will open a windowcontaining the HTML source code of the page.
Web Browsers:
➢ The purpose of a web browser (Chrome, Edge, Firefox, and Safari) is to readHTML documents
and display them correctly.
➢ A browser does not display the HTML tags, but uses them to determine how to display the
document:
Scripting Language:
A script or scripting language is a computer language thatdoes not need the compilation step and is
rather interpreted one by one at runtime.
Types of scripting languages:
There are two types, they are:
1. Client-side scripting language:
A client-side script is a small program (or set of instructions) thatis embedded (or inserted)
into a web page. It is processed within the clientbrowser instead of the web server.
Ex: JavaScript, VBScript, jQuery, HTML (structure), CSS (Design), etc.
Advantages of client-side scripting languages:
1. The client-side scripting language is quite easy to learn and use. It requires minimum
programming knowledge or experienced required.
2. The main advantage of client-side scripting is that it is lightweight and relatively easy to
implement (syntax not too complex). The editing and executingthe code is fast.
3. Data processing is done on the client side from the server, which makes it easier to scale
applications with large numbers of users. Thereby, load on theserver reduces.
4. The client-side data validation can be possible using the client-side scriptinglanguage like
JavaScript.
5. The execution of client-side script is more quickly because once the script is downloaded from
the server; it is executed by the browser directly on the user’scomputer.
6. Mathematical assessment is also possible using client-side scripting.
7. The client-side programming helps to perform the complex tasks in relativelyfew steps.
8. Script code only executed by the browser without connecting the server.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
4
9. It takes too less time to execute script code.
10. Browser respond immediately when user presses any key, mouse movement,clicks, etc.
Disadvantages of client-side scripting languages:
There are certain disadvantages of client-side scripting that are as follows:
1. The main disadvantage of client-side scripting is that it is unsecure because thecode is sent as is to
the client and, therefore, visible to it if the client looks at the sources of his web page. In short,
code is usually visible.
2. Client-side programming cannot be used if we need to access databases orneeds to transmit
sensitive data over the internet.
3. There is no guarantee that user has enabled JavaScript on his computer’sbrowser. Therefore, any
required functionality must be loaded on the serverdespite the possibility that it could be
offloaded.
4. The smooth running of the script (or program) depends entirely on the client’sbrowser, its
configuration, and security level.
5. The web application based on the heavy JavaScript can be complicated todebug and
maintain.
2. Server-side scripting language:
A server-side script is a program that is executed on the server side when the user request
information. The script do not download at the client side. OR a server-side script is executed by the
web browser.
Ex: PHP, Python, Ruby, ASP.Net, Perl, etc.
Advantages of server-side scripting:
1. Server side scripting executes scripts on server,it reduces the load on user’scomputer.
2. Server-side scripting is used to create database web application.Or
3. It deals with the database.
4. Server-side scripts are used to hide scripts from the users.
5. Server scripts are used to generate dynamic website easily in which admin canalter the code at
any time.
6. Server scripts do not depend on browser therefore; we do not need to worryabout version of
browsers.
7. Server-side scripts are used to perform complex tasks.
8. It is easy to learn and use.
9. Server-side script cannot be disabled at the client side.
10. Server-side scripting is more secure than client-side scripting.10.It provides
code reusability.
Disadvantages of server-side scripting:
1. Web Server scripts are difficult to debug.
2. We need a high configuration server to use server-side scripting.
3. Server-side scripting is slower than client-side scripting.
4. It takes more time to execute scripts than client-side scripting.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
5
Difference between Client-Side V/S Server-Side Client side
Client Side
1. It involves web browser.
2. All the code resides on a web browser.
3. Cannot connect to the database.
4. Response is fast.
5. It is less secure.
6. Use to develop frontend applications.
Ex: Users form etc.
Server Side
1. It involves web server.
2. User web browser makes a request to
the server.
3. Can connect to the database.
4. Response is slow.
5. It is more secure.
6. Use to develop backend applications.
Ex: Dynamic Websites etc.
Client-side scripting technologies:
JavaScript
➢ JavaScript (JS) is a lightweight, interpreted, or just-in-time compiledprogramming
language with first-class functions.
➢ It is most well known as the scripting language for Web pages.
➢ JavaScript is very easy to implement because it is integrated with HTML.It is open and cross-
platform.
➢ As of 2022, 98% of websites use JavaScript on the client side for webpage behavior. All major web
browsers have a dedicated JavaScriptengine to execute the code on users' devices.
Ex: <script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
VBScript
➢ Microsoft develops VBScript (visual Basic Script) with the intention ofdeveloping dynamic web
pages.
➢ It is client-side scripting language like JavaScript.
➢ VBScript is a light version of Microsoft Visual Basic. The syntax of VBScript is very similar to that
of Visual Basic. If you want your webpageto be more lively and interactive, then you can incorporate
VBScript in your code.
➢ VBScript is just a scripting language. So,it cannot run its code on its own.It needs a bigger
programming language to host it.
Ex: <script type="text/vbscript">
document.write("Yes!!! I have started learning VBScript.")
</script>
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
6
AJAX
➢ It stands for Asynchronous JavaScript and XML.
➢ AJAX is a new technique for creating better, faster, and more interactive web applications with
the help of XML, HTML, CSS, and Java Script.
jQuery
➢ Good for highly interactive web applications.
➢ Open source and free to use.
➢ Powerful theme mechanism.
➢ Stable and maintenance friendly.
➢ Extensive browser support.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
7
Unit-2
Introduction to C#
Overview of C#
➢ C# is pronounced as "C-Sharp".
➢ It was created by Microsoft Corporation and led by Anders Hejlsberg,which runs on the
.NET Framework.
➢ It is an object-oriented programming language, which provides all the oopconcepts to the user.
➢ C# has roots from the C family, and the language is close to other popularlanguages like C++
and Java.
➢ The first version of C# was released in the year 2002. The latest version of
➢ C# 11, was released in November 2022.
➢ It is easy to learn and use.
➢ C# provides reusability.
C# is used for:
➢ Mobile applications
➢ Desktop applications
➢ Web applications
➢ Web services
➢ Web sites
➢ Games
➢ VR
➢ Database applications, etc.
Why Use C#?
• It is one of the most popular programming languages in the world.
• It is easy to learn and to use.
• It has a huge community support.
• C# is an object-oriented language, which gives a clear structure to programs and allows
code to be reused, lowering development costs.
• As C# is close to C, C++ and Java, it makes it easy for programmers toswitch to C# or vice
versa.
Literals: The fixed values are called literals. The constants refer to fixed values that the program may
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
8
not alter during its execution. Constants can be of anyof the basic data types like an integer constant, a
floating constant, a character constant, or a string literal. There are also enumeration constants as well.
Integer Literals
An integer literal can be a decimal, or hexadecimal constant. A prefix specifies thebase or radix: 0x
or 0X for hexadecimal, and there is no prefix id for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and canbe in any order.
Here are some examples of integer literals:
Following are other examples of various types of Integer literals:
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part.
You can represent floating point literals either in decimal form or exponential form.
Here are some examples of floating-point literals:
Character Literals
▪ Character literals are enclosed in single quotes.
▪ For example, 'x' and can be stored in a simple variable of char type. A character literal can be a plain
character (such as 'x').
Ex: char ch = 'a';
Escape Sequence: Every escape character can be an literal.
Ex: char ch = 'n';
Unicode Representation: We can specify char literals in Unicode representation ‘uxxxx’. Here xxxx
represents 4 hexadecimal numbers.
Ex: char ch = 'u0061';// Here /u0061 represent a.
String Literals
▪ String literals or constants are enclosed in double quotes " " or with @"".
▪ A string contains characters that are similar to character literals: plain characters, escape sequences,
and universal characters.
Ex: String s1=” Hi….. Welcome to Ballari”;
String s2 =@”BCA DEPARTMENT”;
212 /* Legal */
215u /*Legal*/
0xFeeL /* Legal */
85 /* decimal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
3.14159 /* Legal */
314159E-5F /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
9
Boolean Literals: Only two values are allowed for Boolean literals i.e., true and false.
Ex: bool b = true; bool c = false;
C# Variables:
➢ Variables are containers for storing data values.
➢ In C#, there are different types of variables (defined with different keywords),
for example:
▪ int - stores integers (whole numbers), without decimals, such as 123 or - 123
▪ double - stores floating point numbers, with decimals, such as 19.99 or - 19.99
▪ char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
▪ String - stores text, such as "Hello World". String values are surrounded by double
quotes
▪ bool - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax: type variableName = value;
Where type is a C# type (such as int or string), and variableName is the name of the variable (such as
x or name). The equal sign is used to assign values to the variable.
Examples:
▪ int myNum = 5;
▪ double myDoubleNum = 5.99D;
▪ char myLetter = 'D';
▪ bool myBool = true;
▪ string myText = "Hello";
Constants:
➢ If you don't want others (or yourself) to overwrite existing values, you can add the const keyword in
front of the variable type.
➢ This will declare the variable as "constant", which means unchangeable and read-only:
Example: const int myNum = 15;
myNum = 20; // error
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
10
C# Data Types
A data type specifies the type of data that a variable can store such as integer, floating, character etc.
Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed
programming language because in C#, each type of data (such as integer, character, float, and so forth) is
predefined as part of the programming language and all constants or variables defined for a given program
must be described with one of the data types.
Data types in C# is mainly divided into three categories
▪ Value Data Types
▪ Reference Data Types
▪ Pointer Data Type
1. Value Data Types: In C#, the Value Data Types will directly store the variable value in memory and it
will also accept both signed and unsigned literals. The derived class for these data types are
System.ValueType.
Following is different Value Data Types in C# programming language
Signed & Unsigned Integral Types: There are 8 integral types which provide support for 8-bit, 16-bit, 32-
bit, and 64-bit values in signed or unsigned form.
Alias Type Name Type Size(bits) Range Default Value
Sbyte System.Sbyte signed integer 8 -128 to 127 0
Short System.Int16 signed integer 16 -32768 to 32767 0
Int System.Int32 signed integer 32 -231
to 231
-1 0
Long System.Int64 signed integer 64 -263
to 263
-1 0L
Byte System.byte unsigned integer 8 0 to 255 0
Ushort System.UInt16 unsigned integer 16 0 to 65535 0
Uint System.UInt32 unsigned integer 32 0 to 232
0
Ulong System.UInt64 unsigned integer 64 0 to 263
0
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
11
Floating Point Types: There are 2 floating point data types which contain the decimal point.
Float:
▪ It is 32-bit single-precision floating point type.
▪ It has 7-digit Precision.
▪ To initialize a float variable, use the suffix f or F.
▪ Like, float x = 3.5F;
▪ If the suffix F or f will not use then it is treated as double.
Double:
▪ It is 64-bit double-precision floating point type.
▪ It has 14–15-digit Precision.
▪ To initialize a double variable, use the suffix d or D.
▪ But it is not mandatory to use suffix because by default floating data types are the double type.
Alias Type name Size(bits) Range (aprox) Default Value
float System.Single 32 ±1.5 × 10-45
to ±3.4 × 1038
0.0F
double System.Double 64 ±5.0 × 10-324
to ±1.7 × 10308
0.0D
Decimal Types:
▪ The decimal type is a 128-bit data type suitable for financial and monetary calculations.
▪ It has 28–29-digit Precision.
▪ To initialize a decimal variable, use the suffix m or M.
▪ Like as, decimal x = 300.5m;
▪ If the suffix m or M will not use then it is treated as double.
Alias Type name Size(bits) Range (aprox) Default value
decimal System.Decimal 128 ±1.0 × 10-28
to ±7.9228 × 1028
0.0M
Character Types: The character types represent a UTF-16 code unit or represents the 16-bit Unicode
character.
Alias Type name Size In(Bits) Range Default value
char System.Char 16 U +0000 to U +ffff ‘0’
2. Reference Data Types: The Reference Data Types will contain a memory address of variable value
because the reference types won’t store the variable value directly in memory. The built-in reference
types are string, object.
String: It represents a sequence of Unicode characters and its type name is System.String. So, string and
String are equivalent.
Example:
▪ string s1 = "hello"; // creating through string keyword
▪ String s2 = "welcome"; // creating through String class
Object:
▪ In C#, all types, predefined and user-defined, reference types and value types, inherit directly or
indirectly from Object.
▪ So basically, it is the base class for all the data types in C#.
▪ Before assigning values, it needs type conversion.
▪ When a variable of a value type is converted to object, it’s called boxing.
▪ When a variable of type object is converted to a value type, it’s called unboxing.
▪ Its type name is System.Object.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
12
3. Pointer Data Type:
▪ The Pointer Data Types will contain a memory address of the variable value.
▪ To get the pointer details we have a two symbols ampersand (&) and asterisk (*).
▪ ampersand (&): It is Known as Address Operator.
▪ It is used to determine the address of a variable.
▪ asterisk (*): It also known as Indirection Operator.
▪ It is used to access the value of an address.
Operators
▪ Operators are the foundation of any programming language.
▪ Thus, the functionality of C# language is incomplete without the use of operators.
▪ Operators allow us to perform different kinds of operations on operands.
▪ In C#, operators Can be categorized based upon their different functionality:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Conditional Operator
▪ In C#, Operators can also categorize based upon Number of Operands:
• Unary Operator: Operator that takes one operand to perform the operation.
• Binary Operator: Operator that takes two operands to perform the operation.
• Ternary Operator: Operator that takes three operands to perform the operation.
Arithmetic Operators
▪ These are used to perform arithmetic/mathematical operations on operands.
▪ The Binary Operators falling in this category are:
• Addition: The ‘+’ operator adds two operands. For example, x+y.
• Subtraction: The ‘- ‘operator subtracts two operands. For example, x-y.
• Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
• Division: The ‘/’ operator divides the first operand by the second. For example, x/y.
• Modulus: The ‘%’ operator returns the remainder when first operand is divided by the
second. For example, x%y.
// C# program to demonstrate the working of Binary Arithmetic Operators
using System;
namespace Arithmetic
{
class GFG
{
// Main Function
static void Main (string [] args)
{
int result;
int x = 10, y = 5;
// Addition
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
// Subtraction
result = (x - y);
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
13
Console.WriteLine("Subtraction Operator: " + result);
// Multiplication
result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result);
// Division
result = (x / y);
Console.WriteLine("Division Operator: " + result);
// Modulo
result = (x % y);
Console.WriteLine("Modulo Operator: " + result);
}
}
}
The ones falling into the category of Unary Operators are:
Increment:
▪ The ‘++’ operator is used to increment the value of an integer.
▪ When placed before the variable name (also called pre-increment operator), its value is incremented
instantly. For example, ++x.
▪ And when it is placed after the variable name (also called post-increment operator), its value is
preserved temporarily until the execution of this statement and it gets updated before the execution
of the next statement. For example, x++.
Decrement:
▪ The ‘– ‘operator is used to decrement the value of an integer.
▪ When placed before the variable name (also called pre-decrement operator), its value is decremented
instantly. For example, –x.
▪ And when it is placed after the variable name (also called post-decrement operator), its value is
preserved temporarily until the execution of this statement and it gets updated before the execution
of the next statement. For example, x–.
Relational Operators:
▪ Relational operators are used for comparison of two values.
▪ Let’s see them one by one:
• ‘=='(Equal To) operator checks whether the two given operands are equal or not. If so, it returns
true. Otherwise, it returns false. For example, 5==5 will return true.
• ‘! ='(Not Equal To) operator checks whether the two given operands are equal or not. If not, it
returns true. Otherwise, it returns false. It is the exact boolean complement of the ‘==’ operator.
For example, 5! =5 will return false.
• ‘>'(Greater Than) operator checks whether the first operand is greater than the second operand. If
so, it returns true. Otherwise, it returns false. For example, 6>5 will return true.
• ‘< ‘(Less Than) operator checks whether the first operand is lesser than the second operand. If so,
it returns true. Otherwise, it returns false. For example, 6<5 will return false.
• ‘>='(Greater Than Equal To) operator checks whether the first operand is greater than or equal to
the second operand. If so, it returns true. Otherwise, it returns false. For example, 5>=5 will
return true.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
14
• ‘<='(Less Than Equal To) operator checks whether the first operand is lesser than or equal to the
second operand. If so, it returns true. Otherwise, it returns false. For example, 5<=5 will also
return true.
// C# program to demonstrate the working
// of Relational Operators
using System;
namespace Relational {
class demo {
// Main Function
static void Main(string[] args)
{
bool result;
int x = 5, y = 10;
// Equal to Operator
result = (x == y);
Console.WriteLine("Equal to Operator: " + result);
// Greater than Operator
result = (x > y);
Console.WriteLine("Greater than Operator: " + result);
// Less than Operator
result = (x < y);
Console.WriteLine("Less than Operator: " + result);
// Greater than Equal to Operator
result = (x >= y);
Console.WriteLine("Greater than or Equal to: "+ result);
// Less than Equal to Operator
result = (x <= y);
Console.WriteLine("Lesser than or Equal to: "+ result);
// Not Equal To Operator
result = (x != y);
Console.WriteLine("Not Equal to Operator: " + result);
}
}
}
Logical Operators: They are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition in consideration. They are described below:
• Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are
satisfied. Otherwise, it returns false. For example, a && b returns true when both a and b are
true (i.e., non-zero).
• Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in
consideration is satisfied. Otherwise, it returns false. For example, a || b returns true if one of a
or b is true (i.e., non-zero). Of course, it returns true when both a and b are true.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
15
• Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied.
Otherwise, it returns false. For example:! a returns true if a is false, i.e. when a=0.
Example:
// C# program to demonstrate the working
// of Logical Operators
using System;
namespace Logical {
class demo {
// Main Function
static void Main(string[] args)
{
bool a = true,b = false, result;
// AND operator
result = a && b;
Console.WriteLine("AND Operator: " + result);
// OR operator
result = a || b;
Console.WriteLine("OR Operator: " + result);
// NOT operator
result = !a;
Console.WriteLine("NOT Operator: " + result);
}
}
}
Bitwise Operators
▪ In C#, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations.
Following are the bitwise operators:
• & (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers.
The result of AND is 1 only if both bits are 1.
• | (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The
result of OR is 1 any of the two bits is 1.
• ^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers.
The result of XOR is 1 if the two bits are different.
• << (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand
decides the number of places to shift.
• >> (right shift) Takes two numbers, right shifts the bits of the first operand, the second
operand decides the number of places to shift.
Example:
// C# program to demonstrate the working
// of Bitwise Operators
using System;
namespace Bitwise {
class demo {
// Main Function
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
16
static void Main(string[] args)
{
int x = 5, y = 10, result;
// Bitwise AND Operator
result = x & y;
Console.WriteLine("Bitwise AND: " + result);
// Bitwise OR Operator
result = x | y;
Console.WriteLine("Bitwise OR: " + result);
// Bitwise XOR Operator
result = x ^ y;
Console.WriteLine("Bitwise XOR: " + result);
// Bitwise AND Operator
result = ~x;
Console.WriteLine("Bitwise Complement: " + result);
// Bitwise LEFT SHIFT Operator
result = x << 2;
Console.WriteLine("Bitwise Left Shift: " + result);
// Bitwise RIGHT SHIFT Operator
result = x >> 2;
Console.WriteLine("Bitwise Right Shift: " + result);
}
}
}
Assignment Operators
▪ Assignment operators are used to assigning a value to a variable.
▪ The left side operand of the assignment operator is a variable and right-side operand of the
assignment operator is a value.
▪ The value on the right side must be of the same data-type of the variable on the left side otherwise
the compiler will raise an error.
▪ Different types of assignment operators are shown below:
• “=” (Simple Assignment): This is the simplest assignment operator. This operator is used to
assign the value on the right to the variable on the left.
Example:
o a = 10;
o b = 20;
o ch = 'y';
• “+=” (Add Assignment): This operator is combination of ‘+’ and ‘=’ operators. This operator
first adds the current value of the variable on left to the value on the right and then assigns the
result to the variable on the left.
Example:
o (a += b) can be written as (a = a + b)
o If initially value stored in a is 5. Then (a += 6) = 11.
• “-=” (Subtract Assignment): This operator is combination of ‘-‘ and ‘=’ operators. This
operator first subtracts the current value of the variable on left from the value on the right and
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
17
then assigns the result to the variable on the left.
Example:
o (a -= b) can be written as (a = a - b)
o If initially value stored in a is 8. Then (a -= 6) = 2.
• “*=” (Multiply Assignment): This operator is combination of ‘*’ and ‘=’ operators. This
operator first multiplies the current value of the variable on left to the value on the right and
then assigns the result to the variable on the left.
Example:
o (a *= b) can be written as (a = a * b)
o If initially value stored in a is 5. Then (a *= 6) = 30.
• “/=” (Division Assignment): This operator is combination of ‘/’ and ‘=’ operators. This
operator first divides the current value of the variable on left by the value on the right and then
assigns the result to the variable on the left.
Example:
o (a /= b) can be written as (a = a / b)
o If initially value stored in a is 6. Then (a /= 2) = 3.
• “%=” (Modulus Assignment): This operator is combination of ‘%’ and ‘=’ operators. This
operator first modulo the current value of the variable on left by the value on the right and then
assigns the result to the variable on the left.
Example:
o (a %= b) can be written as (a = a % b)
o If initially value stored in a is 6. Then (a %= 2) = 0.
• “<<=” (Left Shift Assignment): This operator is combination of ‘<< ‘and ‘=’ operators. This
operator first Left shift the current value of the variable on left by the value on the right and
then assigns the result to the variable on the left.
Example:
o (a <<= 2) can be written as (a = a << 2)
o If initially value stored in a is 6. Then (a <<= 2) = 24.
• “>>=” (Right Shift Assignment): This operator is combination of ‘>>’ and ‘=’ operators. This
operator first Right shift the current value of the variable on left by the value on the right and
then assigns the result to the variable on the left.
Example:
o (a >>= 2) can be written as (a = a >> 2)
o If initially value stored in a is 6. Then (a >>= 2) = 1.
• “&=” (Bitwise AND Assignment): This operator is combination of ‘&’ and ‘=’ operators. This
operator first “Bitwise AND” the current value of the variable on the left by the value on the
right and then assigns the result to the variable on the left.
Example:
o (a &= 2) can be written as (a = a & 2)
o If initially value stored in a is 6. Then (a &= 2) = 2.
• “^=” (Bitwise Exclusive OR): This operator is combination of ‘^’ and ‘=’ operators. This
operator first “Bitwise Exclusive OR” the current value of the variable on left by the value on
the right and then assigns the result to the variable on the left.
Example:
o (a ^= 2) can be written as (a = a ^ 2)
o If initially value stored in a is 6. Then (a ^= 2) = 4.
• “|=” (Bitwise Inclusive OR): This operator is combination of ‘|’ and ‘=’ operators. This
operator first “Bitwise Inclusive OR” the current value of the variable on left by the value on
the right and then assigns the result to the variable on the left.
Example:
o (a |= 2) can be written as (a = a | 2)
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
18
o If initially, value stored in a is 6. Then (a |= 2) = 6.
Example:
// C# program to demonstrate the working
// of Assignment Operators
using System;
namespace Assignment {
class demo {
// Main Function
static void Main(string[] args)
{
// initialize variable x
// using Simple Assignment
// Operator "="
int x = 15;
// it means x = x + 10
x += 10;
Console.WriteLine("Add Assignment Operator: " + x);
// initialize variable x again
x = 20;
// it means x = x - 5
x -= 5;
Console.WriteLine("Subtract Assignment Operator: " + x);
// initialize variable x again
x = 15;
// it means x = x * 5
x *= 5;
Console.WriteLine("Multiply Assignment Operator: " + x);
// initialize variable x again
x = 25;
// it means x = x / 5
x /= 5;
Console.WriteLine("Division Assignment Operator: " + x);
// initialize variable x again
x = 25;
// it means x = x % 5
x %= 5;
Console.WriteLine("Modulo Assignment Operator: " + x);
// initialize variable x again
x = 8;
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
19
// it means x = x << 2
x <<= 2;
Console.WriteLine("Left Shift Assignment Operator: " + x);
// initialize variable x again
x = 8;
// it means x = x >> 2
x >>= 2;
Console.WriteLine("Right Shift Assignment Operator: " + x);
// initialize variable x again
x = 12;
// it means x = x >> 4
x &= 4;
Console.WriteLine("Bitwise AND Assignment Operator: " + x);
// initialize variable x again
x = 12;
// it means x = x >> 4
x ^= 4;
Console.WriteLine("Bitwise Exclusive OR Assignment Operator: " + x);
// initialize variable x again
x = 12;
// it means x = x >> 4
x |= 4;
Console.WriteLine("Bitwise Inclusive OR Assignment Operator: " + x);
}
}
}
Conditional Operator:
➢ It is ternary operator which is a shorthand version of if-else statement.
➢ It has three operands and hence the name ternary.
➢ It will return one of two values depending on the value of a Boolean expression.
Syntax: condition ? first_expression : second_expression;
Explanation:
▪ condition: It must be evaluated to true or false.
▪ If the condition is true.
▪ first_expression is evaluated and becomes the result.
▪ If the condition is false,
▪ second_expression is evaluated and becomes the result.
Example:
// C# program to demonstrate the working
// of Conditional Operator
using System;
namespace Conditional {
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
20
class demo {
// Main Function
static void Main(string[] args)
{
int x = 5, y = 10, result;
// To find which value is greater
// Using Conditional Operator
result = x > y ? x : y;
// To display the result
Console.WriteLine("Result: " + result);
// To find which value is greater
// Using Conditional Operator
result = x < y ? x : y;
// To display the result
Console.WriteLine("Result: " + result);
}
}}
Decision Making: in programming is similar to decision making in real life. In programming too, a
certain block of code needs to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of program based on
certain conditions. These are used to cause the flow of execution to advance and branch based on changes
to the state of a program.
The conditional statements of C#:
➢ if
➢ if-else
➢ if-else-if
➢ Nested if
➢ Switch
➢ Nested switch
if Statement:
➢ The if statement checks the given condition.
➢ If the condition evaluates to be true then the block of code/statements will execute otherwise not.
Syntax:
if(condition)
{
//code to be executed
}
Note: If the curly brackets { } are not used with if statements than the statement just next to it is only
considered associated with the if statement.
Example:
if (condition)
statement 1;
statement 2;
In this example, only statement 1 is considered to be associated with the if statement.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
21
Flowchart:
Example:
// C# program to illustrate if statement
using System;
public class demo {
public static void Main(string[] args)
{
string name = "smdc";
if (name == "smdc") {
Console.WriteLine("smdc college");
}
}
}
Output: Smdc college
➢ if else Statement
The if statement evaluates the code if the condition is true but what if the condition is not true, here
comes the else statement.
➢ It tells the code what to do when the if condition is false.
➢ Syntax:
if(condition)
{
// code if condition is true
}
else
{
// code if condition is false
}
Flowchart:
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
22
Example:
// C# program to illustrate
// if-else statement
using System;
public class demo {
public static void Main(string[] args)
{
string name = "smdc";
if (name == "smdc") {
Console.WriteLine("Smdc College");
}
else {
Console.WriteLine("smdc");
}
}}
Output: Smdc College
if – else – if/else_if ladder Statement
➢ The if-else-if ladder statement executes one condition from multiple statements.
➢ The execution starts from top and checked for each if condition.
➢ The statement of if block will be executed which evaluates to be true.
➢ If none of the if condition evaluates to be true then the last else block is evaluated.
Syntax:
if(condition1)
{
// code to be executed if condition1 is true
}
else if(condition2)
{
// code to be executed if
condition2 is true
}
else if(condition3)
{
// code to be executed if
condition3 is true
}
...
else
{
// code to be executed if all
the conditions are false
}
Example:
Flowchart:
// C# program to illustrate
// if-else-if ladder
using System;
class demo {
public static void Main(String[] args)
{
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
23
int i = 20;
if (i == 10)
Console.WriteLine("i is 10");
else if (i == 15)
Console.WriteLine("i is 15");
else if (i == 20)
Console.WriteLine("i is 20");
else
Console.WriteLine("i is not present");
}
}
Output:
i is 20
Nested – If Statement
➢ if statement inside an if statement is known as
nested if.
➢ if statement in this case is the target of another
if or else statement.
➢ When more than one condition needs to be true
and one of the condition is the sub-condition of
parent condition, nested if can be used.
Syntax:
if (condition1)
{
// code to be executed
// if condition2 is true
if (condition2)
{
// code to be executed
// if condition2 is true
}
} Flowchart:
Example:
// C# program to illustrate
// nested-if statement
using System;
class demo {
public static void Main(String[] args)
{
int i = 10;
if (i == 10) {
// Nested - if statement
// Will only be executed if statement
// above it is true
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
24
if (i < 12)
Console.WriteLine("i is smaller than 12 too");
else
Console.WriteLine("i is greater than 15");
}
}
}
Output: i is smaller than 12 too
Switch Statement Flow Diagram of Switch – case:
➢ Switch statement is an alternative to long if-else-if ladders.
➢ The expression is checked for different
cases and the one match is executed.
➢ Break statement is used to move out of
the switch.
➢ If the break is not used, the control will
flow to all cases below it until break is
found or switch comes to an end.
➢ There is default case (optional) at the
end of switch, if none of the case
matches then default case is executed.
Syntax:
switch (expression)
{
case value1: // statement sequence
break;
case value2: // statement sequence
break;
.
.
.
case valueN: // statement sequence
break;
default: // default statement sequence
}
Example:
// C# example for switch case
using System;
public class demo
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
25
{
public static void Main(String[] args)
{
int number = 30;
switch(number)
{
case 10: Console.WriteLine("case 10");
break;
case 20: Console.WriteLine("case 20");
break;
case 30: Console.WriteLine("case 30");
break;
default: Console.WriteLine("None matches");
break;
}
}
}
Output: case 30
Nested switch
➢ Nested Switch case are allowed in C#.
➢ In this case, switch is present inside other switch case.
➢ Inner switch is present in one of the cases in parent switch.
Example:
// C# example for nested switch case
using System;
public class demo
{
public static void Main(String[] args)
{
int j = 5;
switch (j)
{
case 5: Console.WriteLine(5);
switch (j - 1)
{
case 4: Console.WriteLine(4);
switch (j - 2)
{
case 3: Console.WriteLine(3);
break;
}
break;
}
break;
case 10: Console.WriteLine(10);
break;
case 15: Console.WriteLine(15);
break;
default: Console.WriteLine(100);
break;
}
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
26
}
}
Output:
5
4
3
Looping Statements
➢ Looping in a programming language is a way to execute a statement or a set of statements multiple
times depending on the result of the
condition to be evaluated to execute
statements.
➢ The result condition should be true to
execute statements within loops.
➢ Loops are mainly divided into two
categories:
Entry Controlled Loops:
➢ The loops in which condition to be tested
is present in beginning of loop body are
known as Entry Controlled Loops.
➢ while loop and for loop are entry-
controlled loops.
1. while loop:
The test condition is given in the beginning
of the loop and all statements are executed till the
given boolean condition satisfies when the condition becomes false, the control will be out from the while
loop.
Syntax:
while (boolean condition)
{
loop statements...
}
Example: Flowchart:
// C# program to illustrate while loop
using System;
class whileLoopDemo
{
public static void Main()
{
int x = 1;
// Exit when x becomes greater than 4
while (x <= 4)
{
Console.WriteLine("smdc college");
// Increment the value of x for
// next iteration
x++;
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
27
}
}
}
Output:
Smdc college
Smdc college
Smdc college
Smdc college
2. for loop
➢ for loop has similar functionality as while loop but with
different syntax.
➢ for loops are preferred when the number of times loop
statements are to be executed is known beforehand.
➢ The loop variable initialization, condition to be tested, and
increment/decrement of the loop variable is done in one line in
for loop thereby providing a shorter, easy to debug structure of
looping.
Syntax:
for (loop variable initialization; testing condition;
increment / decrement)
{
// statements to be executed
}
1. Initialization of loop variable: Th expression / variable controlling the loop is initialized here. It is the
starting point of for loop. An already declared variable can be used or a variable can be declared, local to
loop only.
3. Testing Condition: The testing condition to execute statements of loop. It is used for testing the exit
condition for a loop. It must return a boolean value true or false. When the condition became false the
control will be out from the loop and for loop ends. Flowchart:
2. Increment / Decrement: The loop variable is incremented/decremented according to the requirement
and the control then shifts to the testing condition again.
Note: Initialization part is evaluated only once when the for loop starts.
Example:
// C# program to illustrate for loop.
using System;
class forLoopDemo
{
public static void Main()
{
// for loop begins when x=1
// and runs till x <=4
for (int x = 1; x <= 4; x++)
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
28
Console.WriteLine("smdc college");
}
}
Exit Controlled Loops:
➢ The loops in which the testing condition is present at the end of loop body are termed as Exit
Controlled Loops.
➢ do-while is an exit-controlled loop.
Note: In Exit Controlled Loops, loop body will be evaluated for at-least one time as the testing condition is
present at the end of loop body.
3. do-while loop
do while loop is similar to while loop with the only difference that it checks the
condition after executing the statements, i.e it will execute the loop body one time for sure because it checks
the condition after executing the statements.
Syntax:
do
{
statements..
}while (condition);
Example: Flowchart:
// C# program to illustrate do-while loop
using System;
class dowhileloopDemo
{
public static void Main()
{
int x = 21;
do
{
// The line will be printed even
// if the condition is false
Console.WriteLine("smdc college");
x++;
}
while (x < 20);
}
}
Output: Smdc college
4. Infinite Loops:
The loops in which the test condition does not evaluate false ever tend to execute statements
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
29
forever until an external force is used to end it and thus, they are known as infinite loops.
Example:
// C# program to demonstrate infinite loop
using System;
class infiniteLoop
{
public static void Main()
{
// The statement will be printed
// infinite times
for(;;)
Console.WriteLine("This is printed infinite times");
}
}
Output:
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
..........
5. Nested Loops: When loops are present inside the other loops, it is known as nested loops.
Example:
// C# program to demonstrate nested loops
using System;
class nestedLoops
{
public static void Main()
{
// loop within loop printing smdc college
for(int i = 2; i < 3; i++)
for(int j = 1; j < i; j++)
Console.WriteLine("smdc college");
}
}
Output: Smdc college
Continue Statement: Continue statement is used to skip over the execution part of loop on a certain
condition and move the flow to next updation part.
Flowchart:
Example:
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
30
// C# program to demonstrate continue statement
using System;
class demoContinue
{
public static void Main()
{
// because of continue statement
for(int i = 1; i < 3; i++)
{
if(i == 2)
continue;
Console.WriteLine("smdc college");
}
}
}
Output: Smdc college
Jump Statements (Break, Continue, Goto, Return and Throw)
In C#, Jump statements are used to
transfer control from one point to another
point in the program due to some specified
code while executing the program. There are
five keywords in the Jump Statements:
➢ break
➢ continue
➢ goto
➢ return
➢ throw
break statement:
The break statement is used to
terminate the loop or statement in which it
present. After that, the control will pass to the statements that present after the break statement, if available.
If the break statement presents in the nested loop, then it terminates only those loops which contains break
statement.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
31
Flowchart:
continue statement:
This statement is used to skip over the execution part of the loop on a certain condition. After that, it
transfers the control to the beginning of the loop. Basically, it skips its following statements and continues
with the next iteration of the loop.
Flowchart:
Example:
// C# program to illustrate the
// use of continue statement
using System;
class demo {
// Main Method
public static void Main()
{
// This will skip 4 to print
for (int i = 1; i <= 10; i++) {
// if the value of i becomes 4 then
// it will skip 4 and send the
// transfer to the for loop and
// continue with 5
if (i == 4)
continue;
Console.WriteLine(i);
}
}
}
Output:
1
2
3
5
6
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
32
7
8
9
10
goto statement:
This statement is used to transfer control to the labeled statement in the program. The label is the
valid identifier and placed just before the statement from where the control is transferred.
Example: Flowchart:
// C# program to illustrate the
// use of goto statement
using System;
class demo {
// Main Method
static public void Main()
{
int number = 20;
switch (number) {
case 5:
Console.WriteLine("case 5");
break;
case 10:
Console.WriteLine("case 10");
break;
case 20:
Console.WriteLine("case 20");
// goto statement transfer
// the control to case 5
goto case 5;
default:
Console.WriteLine("No match found");
break;
}
}
}
Output:
case 20
case 5
return statement:
This statement terminates the execution of the method and returns the control to the calling
method. It returns an optional value. If the type of method is void, then the return statement can be
excluded.
Example:
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
33
// C# program to illustrate the
// use of return statement
using System;
class demo {
// creating simple addition function
static int Addition(int a)
{
// add two value and
// return the result of addition
int add = a + a;
// using return statement
return add;
}
// Main Method
static public void Main()
{
int number = 2;
// calling addition function
int result = Addition(number);
Console.WriteLine("The addition is {0}", result);
}
}
Output:
The addition is 4
throw statement:
This is used to create an object of any valid exception class with the help of new keyword manually.
The valid exception must be derived from the Exception class.
Example:
// C# Program to illustrate the use
// of throw keyword
using System;
class demo {
// taking null in the string
static string sub = null;
// method to display subject name
static void displaysubject(string sub1)
{
if (sub1 == null)
throw new NullReferenceException("Exception Message");
}
// Main Method
static void Main(string[] args)
{
// using try catch block to
// handle the Exception
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
34
try
{
// calling the static method
displaysubject(sub);
}
catch(Exception exp)
{
Console.WriteLine(exp.Message );
}
}
}
Output:
Exception Message
Methods
➢ A method is a group of statements that together perform a task.
➢ Every C# program has at least one class with a method named Main.
➢ To use a method, you need to −
▪ Define the method
▪ Call the method
Defining Methods in C#
➢ When you define a method, you basically declare the elements of its structure.
➢ The syntax for defining a method in C# is as follows −
<Access Specifier> <Return Type> <Method Name>(Parameter List) {
Method Body
}
Following are the various elements of a method −
➢ Access Specifier − This determines the visibility of a variable or a method from another class.
➢ Return type − A method may return a value. The return type is the data type of the value the method
returns.
➢ If the method is not returning any values, then the return type is void.
▪ Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as
any other identifier declared in the class.
▪ Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data
from a method. The parameter list refers to the type, order, and number of the parameters of a
method. Parameters are optional; that is, a method may contain no parameters.
▪ Method body − This contains the set of instructions needed to complete the required activity.
Example:
Following code snippet shows a function FindMax that takes two integer values and returns the
larger of the two. It has public access specifier, so it can be accessed from outside the class using an instance
of the class.
class NumberManipulator {
public int FindMax(int num1, int num2) {
/* local variable declaration */
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
35
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
...
}
Calling Methods in C#
➢ You can call a method using the name of the method. The following example illustrates this –
Example:
using System;
namespace CalculatorApplication {
class NumberManipulator {
public int FindMax(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
static void Main(string[] args) {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
//calling the FindMax method
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Max value is: 200
You can also call public method from other classes by using the instance of the class. For example,
the method FindMax belongs to the NumberManipulator class, you can call it from another class Test.
Example:
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
36
using System;
namespace CalculatorApplication {
class NumberManipulator {
public int FindMax(int num1, int num2) {
/* local variable declaration */
int result;
if(num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
class Test {
static void Main(string[] args) {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
//calling the FindMax method
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Max value is : 200
Recursive Method Call
➢ A method can call itself. This is known as recursion.
➢ Following is an example that calculates factorial for a given number using a recursive function −
using System;
namespace CalculatorApplication {
class NumberManipulator {
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
37
public int factorial(int num) {
/* local variable declaration */
int result;
if (num == 1) {
return 1;
} else {
result = factorial(num - 1) * num;
return result;
}
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
//calling the factorial method {0}", n.factorial(6));
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result –
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
Passing Parameters to a Method
➢ When method with parameters is called, you need to pass the parameters to the method.
➢ There are three ways that parameters can be passed to a method −
Sl.No Mechanism & Description
1
Value parameters
This method copies the actual value of an argument into the formal parameter of the function. In
this case, changes made to the parameter inside the function have no effect on the argument.
2
Reference parameters
This method copies the reference to the memory location of an argument into the formal
parameter. This means that changes made to the parameter affect the argument.
3
Output parameters
This method helps in returning more than one value.
String Operations:
➢ C# string provides various methods to perform different operations on strings.
➢ We will look into some of the commonly used string operations.
1. Get the Length of a string
To find the length of a string, we use the Length property. For example,
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
38
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str = "C# Programming";
Console.WriteLine("string: " + str);
// get length of str
int length = str.Length;
Console.WriteLine("Length: "+ length);
Console.ReadLine();
}
}
}
Output:
string: C# Programming
Length: 14
In the above example, the Length property calculates the total number of characters in the string and returns
it.
2. Join two strings in C#
We can join two strings in C# using the Concat() method.
For example,
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# ";
Console.WriteLine("string str1: " + str1);
// create string
string str2 = "Programming";
Console.WriteLine("string str2: " + str2);
// join two strings
string joinedString = string.Concat(str1, str2);
Console.WriteLine("Joined string: " + joinedString);
Console.ReadLine();
}
}
}
Output:
string str1: C#
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
39
string str2: Programming
Joined string: C# Programming
• In the above example, we have created two strings named str1 and str2.
• Notice the statement, string joinedString = string.Concat(str1, str2);
• Here, the Concat() method joins str1 and str2 and assigns it to the joinedString variable.
• We can also join two strings using the + operator in C#.
3. C# compare two strings
➢ In C#, we can make comparisons between two strings using the Equals() method.
➢ The Equals() method checks if two strings are equal or not.
For example,
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# Programming";
string str2 = "C# Programming";
string str3 = "Programiz";
// compare str1 and str2
Boolean result1 = str1.Equals(str2);
Console.WriteLine("string str1 and str2 are equal: " + result1);
//compare str1 and str3
Boolean result2 = str1.Equals(str3);
Console.WriteLine("string str1 and str3 are equal: " + result2);
Console.ReadLine();
}
}
}
Output:
string str1 and str2 are equal: True
string str1 and str3 are equal: False
In the above example, we have created 3 strings named str1, str2, and str3. Here, we are using the Equals()
method to check if one string is equal to another.
Immutability of String Objects
➢ In C#, strings are immutable.
➢ This means, once we create a string, we cannot change that string.
To understand it, consider an example:
// create string
string str = "Hello ";
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
40
Here, we have created a string variable named str. The variable holds the string "Hello ".
Now suppose we want to change the string str.
// add another string "World"
// to the previous string example
str = string.Concat(str, "World");
Here, we are using the Concat() method to add the string "World" to the previous string str.
But how are we able to modify the string when they are immutable?
Let's see what has happened here,
1. C# takes the value of the string "Hello ".
2. Creates a new string by adding "World" to the string "Hello ".
3. Creates a new string object, gives it a value "Hello World", and stores it in str.
4. The original string, "Hello ", that was assigned to str is released for garbage collection because no
other variable holds a reference to it.
String Escape Sequences
➢ The escape character is used to escape some of the characters present inside a string.
➢ In other words, we use escape sequences to insert special characters inside the string.
Suppose we need to include double quotes inside a string.
// include double quote
string str = "This is the "String" class";
Since strings are represented by double quotes, the compiler will treat "This is the " as the string. And the
above code will cause an error.
To solve this issue, we use the escape character " in C#. For example,
// use the escape character
string str = "This is the "String" class.";
Now by using  before double quote ", we can include it in the string.
Some of the escape sequences in C# are as follows:
Escape Sequence Character Name
' single quote
" double quote
 backslash
0 null
n new line
t horizontal tab
String interpolation
➢ In C#, we can use string interpolation to insert variables inside a string.
➢ For string interpolation, the string literal must begin with the $ character.
For example,
using System;
namespace CsharpString {
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
41
class Test {
public static void Main(string [] args) {
// create string
string name = "Programiz";
// string interpolation
string message = $"Welcome to {name}";
Console.WriteLine(message);
Console.ReadLine();
}
}
}
Output: Welcome to Programiz
In the above example, we are using the name variable inside the message string.
string message = $"Welcome to {name}";
Notice that,
▪ the string literal starts with $
▪ the name variable is placed inside the curly braces {}
Methods of C# string
There are various string methods in C#. Some of them are as follows:
Methods Description
Format() returns a formatted string
Split() splits the string into substring
Substring() returns substring of a string
Compare() compares string objects
Replace() replaces the specified old character with the specified new character
Contains() checks whether the string contains a substring
Join() joins the given strings using the specified separator
Trim() removes any leading and trailing whitespaces
EndsWith() checks if the string ends with the given string
IndexOf() returns the position of the specified character in the string
Remove() returns characters from a string
ToUpper() converts the string to uppercase
ToLower() converts the string to lowercase
PadLeft() returns string padded with spaces or with a specified Unicode character on the left
PadRight() returns string padded with spaces or with a specified Unicode character on the right
StartsWith() checks if the string begins with the given string
ToCharArray() converts the string to a char array
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
42
LastIndexOf() returns index of the last occurrence of a specified string
Structures
➢ In C#, a structure is a value type data type.
➢ It helps you to make a single variable hold related data of various data types.
➢ The struct keyword is used for creating a structure.
➢ Structures are used to represent a record. Suppose you want to keep track of your books in a library.
➢ You might want to track the following attributes about each book −
▪ Title
▪ Author
▪ Subject
▪ Book ID
Defining a Structure
➢ To define a structure, you must use the struct statement.
➢ The struct statement defines a new data type, with more than one member for your program.
For example, here is the way you can declare the Book structure −
struct Books {
public string title;
public string author;
public string subject;
public int book_id;
};
The following program shows the use of the structure −
using System;
struct Books {
public string title;
public string author;
public string subject;
public int book_id;
};
public class testStructure {
public static void Main(string[] args) {
Books Book1; /* Declare Book1 of type Book */
Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "C# Programming";
Book1.author = "vinutha";
Book1.subject = "C# Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Raju";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;
/* print Book1 info */
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
43
Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);
/* print Book2 info */
Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result –
Book 1 title : C# Programming
Book 1 author : vinutha
Book 1 subject : C# Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Raju
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Features of C# Structures
You have already used a simple structure named Books. Structures in C# are quite different from that
in traditional C or C++.
The C# structures have the following features −
➢ Structures can have methods, fields, indexers, properties, operator methods, and events.
➢ Structures can have defined constructors, but not destructors. However, you cannot define a default
constructor for a structure. The default constructor is automatically defined and cannot be changed.
➢ Unlike classes, structures cannot inherit other structures or classes.
➢ Structures cannot be used as a base for other structures or classes.
➢ A structure can implement one or more interfaces.
➢ Structure members cannot be specified as abstract, virtual, or protected.
➢ When you create a struct object using the New operator, it gets created and the appropriate
constructor is called. Unlike classes, structs can be instantiated without using the New operator.
➢ If the New operator is not used, the fields remain unassigned and the object cannot be used until all
the fields are initialized.
➢ Class versus Structure
➢ Classes and Structures have the following basic differences −
➢ classes are reference types and structs are value types
➢ structures do not support inheritance
➢ structures cannot have default constructor
In the light of the above discussions, let us rewrite the previous example −
using System;
struct Books {
private string title;
private string author;
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
44
private string subject;
private int book_id;
public void getValues(string t, string a, string s, int id) {
title = t;
author = a;
subject = s;
book_id = id;
}
public void display() {
Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}", book_id);
}
};
public class testStructure {
public static void Main(string[] args) {
Books Book1 = new Books(); /* Declare Book1 of type Book */
Books Book2 = new Books(); /* Declare Book2 of type Book */
/* book 1 specification */
Book1.getValues("C# Programming",
"vinutha", "C Programming Tutorial",6495407);
/* book 2 specification */
Book2.getValues("Telecom Billing",
"Raju", "Telecom Billing Tutorial", 6495700);
/* print Book1 info */
Book1.display();
/* print Book2 info */
Book2.display();
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result –
Title : C# Programming
Author : vinutha
Subject : C# Programming Tutorial
Book_id : 6495407
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
45
Title : Telecom Billing
Author : Raju
Subject : Telecom Billing Tutorial
Book_id : 6495700
Enums
➢ An enumeration is a set of named integer constants.
➢ An enumerated type is declared using the enum keyword.
➢ C# enumerations are value data type.
➢ In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.
Declaring enum Variable
The general syntax for declaring an enumeration is −
enum <enum_name> {
enumeration list
};
Where,
• The enum_name specifies the enumeration type name.
• The enumeration list is a comma-separated list of identifiers.
Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that
precedes it. By default, the value of the first enumeration symbol is 0.
For example −
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
Example:
The following example demonstrates use of enum variable −
using System;
namespace EnumApplication {
class EnumProgram {
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
static void Main(string[] args) {
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Console.WriteLine("Monday: {0}", WeekdayStart);
Console.WriteLine("Friday: {0}", WeekdayEnd);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result –
Monday: 1
Friday: 5
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
46
OOPS With C#
Class and Object
• Class and Object are the basic concepts of Object-Oriented Programming which revolve around the real-
life entities.
• A class is a user-defined blueprint or prototype from which objects are created.
• Basically, a class combines the fields and methods (member function which defines actions) into a single
unit.
• In C#, classes support polymorphism, inheritance and also provide the concept of derived classes and
base classes.
Declaration of class
• Generally, a class declaration contains only a keyword class, followed by an identifier(name) of the
class.
• But there are some optional attributes that can be used with class declaration according to the application
requirement.
• In general, class declarations can include these components, in order:
Modifiers: A class can be public or internal etc. By default modifier of the class is internal.
Keyword class: A class keyword is used to declare the type class.
Class Identifier: The variable of type class is provided. The identifier (or name of the class) should begin
with an initial letter which should be capitalized by convention.
Base class or Super class: The name of the class’s parent (superclass), if any, preceded by the : (colon).
This is optional.
Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded by the : (colon).
A class can implement more than one interface. This is optional.
Body: The class body is surrounded by { } (curly braces).
Constructors in class are used for initializing new objects. Fields are variables that provide the state of the
class and its objects, and methods are used to implement the behavior of the class and its objects.
Example:
// declaring public class
public class sample
{
// field variable
public int a, b;
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
47
// member function or method
public void display()
{
Console.WriteLine(“Class & Objects in C#”);
}
}
Objects
It is a basic unit of Object-Oriented Programming and represents real-life entities. A typical C# program
creates many objects, which as you know, interact by invoking methods. An object consists of:
State: It is represented by attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object with other
objects.
Identity: It gives a unique name to an object and enables one object to interact with other objects.
Consider Dog as an object and see the below diagram for its identity, state, and behavior.
Objects correspond to things found in the real world. For example, a graphics program may have objects
such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping cart”,
“customer”, and “product”.
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated. All the instances share the attributes
and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A
single class may have any number of instances.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
48
Example:
As we declare variables like (type name;). This notifies the compiler that we will use the name to refer to
data whose type is type. With a primitive variable, this declaration also reserves the proper amount of
memory for the variable. So for reference variable, the type must be strictly a concrete class name.
Dog tuffy;
If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an object is
actually created and assigned to it. Simply declaring a reference variable does not create an object.
Initializing an object
The new operator instantiates a class by allocating memory for a new object and returning a reference to that
memory. The new operator also invokes the class constructor.
Example:
C#
// C# program to illustrate the
// Initialization of an object
using System;
// Class Declaration
public class Dog {
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
49
}
// Property 1
public String GetName()
{
return name;
}
// Property 2
public String GetBreed()
{
return breed;
}
// Property 3
public int GetAge()
{
return age;
}
// Property 4
public String GetColor()
{
return color;
}
// Method 1
public String ToString()
{
return ("Hi my name is " + this.GetName()
+ ".nMy breed, age and color are " + this.GetBreed()
+ ", " + this.GetAge() + ", " + this.GetColor());
}
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
50
// Main Method
public static void Main(String[] args)
{
// Creating object
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
Console.WriteLine(tuffy.ToString());
}
}
Output:
Hi my name is tuffy.
My breed, age and color are papillon, 5, white
Inheritance
• In C#, inheritance is a process in which one object acquires all the properties and behaviors of its parent
object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which is
defined in other class.
• In C#, the class which inherits the members of another class is called derived class and the class whose
members are inherited is called base class. The derived class is the specialized class for the base class.
Advantage of C# Inheritance
• Code reusability: Now you can reuse the members of your parent class. So, there is no need to define
the member again. So less code is required in the class.
• C# Single Level Inheritance Example: Inheriting Fields
• When one class inherits another class, it is known as single level inheritance. Let's see the example of
single level inheritance which inherits the fields only.
using System;
public class Employee
{
public float salary = 40000;
}
public class Programmer: Employee
{
public float bonus = 10000;
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
51
}
class TestInheritance{
public static void Main(string[] args)
{
Programmer p1 = new Programmer();
Console.WriteLine("Salary: " + p1.salary);
Console.WriteLine("Bonus: " + p1.bonus);
}
}
Output:
Salary: 40000
Bonus: 10000
In the above example, Employee is the base class and Programmer is the derived class.
C# Single Level Inheritance Example: Inheriting Methods
Let's see another example of inheritance in C# which inherits methods only.
using System;
public class Animal
{
public void eat() { Console.WriteLine("Eating..."); }
}
public class Dog: Animal
{
public void bark() { Console.WriteLine("Barking..."); }
}
class TestInheritance2{
public static void Main(string[] args)
{
Dog d1 = new Dog();
d1.eat();
d1.bark();
}
}
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
52
Output:
Eating...
Barking...
C# Multi Level Inheritance Example
When one class inherits another class which is further inherited by another class, it is known as multi level
inheritance in C#. Inheritance is transitive so the last derived class acquires all the members of all its base
classes.
Let's see the example of multi level inheritance in C#.
using System;
public class Animal
{
public void eat() { Console.WriteLine("Eating..."); }
}
public class Dog: Animal
{
public void bark() { Console.WriteLine("Barking..."); }
}
public class BabyDog : Dog
{
public void weep() { Console.WriteLine("Weeping..."); }
}
class TestInheritance2{
public static void Main(string[] args)
{
BabyDog d1 = new BabyDog();
d1.eat();
d1.bark();
d1.weep();
}
}
Output:
Eating...
Barking...
Weeping...
Note: Multiple inheritance is not supported in C# through class.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
53
C# Aggregation (HAS-A Relationship)
In C#, aggregation is a process in which one class defines another class as any entity reference. It is another
way to reuse the class. It is a form of association that represents HAS-A relationship.
C# Aggregation Example
Let's see an example of aggregation where Employee class has the reference of Address class as data
member. In such way, it can reuse the members of Address class.
using System;
public class Address
{
public string addressLine, city, state;
public Address(string addressLine, string city, string state)
{
this.addressLine = addressLine;
this.city = city;
this.state = state;
}
}
public class Employee
{
public int id;
public string name;
public Address address;//Employee HAS-A Address
public Employee(int id, string name, Address address)
{
this.id = id;
this.name = name;
this.address = address;
}
public void display()
{
Console.WriteLine(id + " " + name + " " +
address.addressLine + " " + address.city + " " + address.state);
}
}
public class TestAggregation
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
54
{
public static void Main(string[] args)
{
Address a1=new Address("G-13, Sec-3","Noida","UP");
Employee e1 = new Employee(1,"Sonoo",a1);
e1.display();
}
}
Output:
1 Sonoo G-13 Sec-3 Noida UP
Inheritance and an "is a" relationship
Ordinarily, inheritance is used to express an "is a" relationship between a base class and one or more derived
classes, where the derived classes are specialized versions of the base class; the derived class is a type of the
base class. For example, the Publication class represents a publication of any kind, and
the Book and Magazine classes represent specific types of publications.
Note
A class or struct can implement one or more interfaces. While interface implementation is often presented as
a workaround for single inheritance or as a way of using inheritance with structs, it is intended to express a
different relationship (a "can do" relationship) between an interface and its implementing type than
inheritance. An interface defines a subset of functionality (such as the ability to test for equality, to compare
or sort objects, or to support culture-sensitive parsing and formatting) that the interface makes available to
its implementing types.
C# Polymorphism
Polymorphism and Overriding Methods
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other
by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit fields and methods from another
class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action
in different ways.
C# Member Overloading
If we create two or more members having same name but different in number or type of parameter, it is
known as member overloading. In C#, we can overload:
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
55
methods,
constructors, and
indexed properties
It is because these members have parameters only.
C# Method Overloading
Having two or more methods with same name but different in parameters, is known as method overloading
in C#.
The advantage of method overloading is that it increases the readability of the program because you don't
need to use different names for same action.
using System;
public class Cal{
public static int add(int a,int b){
return a + b;
}
public static int add(int a, int b, int c)
{
return a + b + c;
}
}
public class TestMemberOverloading
{
public static void Main()
{
Console.WriteLine(Cal.add(12, 23));
Console.WriteLine(Cal.add(12, 23, 25));
}
}
Output:
35
60
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
56
C# Method Overriding
If derived class defines same method as defined in its base class, it is known as method overriding in C#. It
is used to achieve runtime polymorphism. It enables you to provide specific implementation of the method
which is already provided by its base class.
To perform method overriding in C#, you need to use virtual keyword with base class method
and override keyword with derived class method.
C# Method Overriding Example
Let's see a simple example of method overriding in C#. In this example, we are overriding the eat() method
by the help of override keyword.
class Parent
{
public virtual void Demo() // base class
{
Console.WriteLine(“This is parent”);
}
}
class Child: Parent
{
public override void Demo() // derived class
{
Console.WriteLine(“This is child”);
}
}
public static void main()
{
Child c=new child();
c.Demo();
}
Interfaces
Another way to achieve abstraction in C#, is with interfaces.
An interface is a completely "abstract class", which can only contain abstract methods and properties (with
empty bodies):
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
57
Example
// interface
interface Animal
{
void animalSound(); // interface method (does not have a body)
void run(); // interface method (does not have a body)
}
It is considered good practice to start with the letter "I" at the beginning of an interface, as it makes it easier
for yourself and others to remember that it is an interface and not a class.
By default, members of an interface are abstract and public.
Note: Interfaces can contain properties and methods, but not fields.
To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class.
To implement an interface, use the : symbol (just like with inheritance). The body of the interface method is
provided by the "implement" class. Note that you do not have to use the override keyword when
implementing an interface:
Example
// Interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}
// Pig "implements" the IAnimal interface
class Pig : IAnimal
{
public void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
58
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}
Notes on Interfaces:
Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to
create an "IAnimal" object in the Program class)
• Interface methods do not have a body - the body is provided by the "implement" class
• On implementation of an interface, you must override all of its methods
• Interfaces can contain properties and methods, but not fields/variables
• Interface members are by default abstract and public
• An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When to Use Interfaces?
1) To achieve security - hide certain details and only show the important details of an object (interface).
2) C# does not support "multiple inheritance" (a class can only inherit from one base class). However, it can
be achieved with interfaces, because the class can implement multiple interfaces.
Note: To implement multiple interfaces, separate them with a comma (see example below).
interface IFirstInterface
{
void myMethod(); // interface method
}
interface ISecondInterface
{
void myOtherMethod(); // interface method
}
// Implement multiple interfaces
class DemoClass : IFirstInterface, ISecondInterface
{
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
59
public void myMethod()
{
Console.WriteLine("Some text..");
}
public void myOtherMethod()
{
Console.WriteLine("Some other text...");
}
}
class Program
{
static void Main(string[] args)
{
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
C# - 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.
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.
Syntax
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
60
Assuming a block raises an exception, a method catches an exception using a combination of the try and
catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following −
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
}
You can list down multiple catch statements to catch different type of exceptions in case your try block
raises more than one exception in different situations.
Exception Classes in C#
C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly
derived from the System.Exception class. Some of the exception classes derived from the System.Exception
class are the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. Hence the
exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class −
Sr.No. Exception Class & Description
1 System.IO.IOException
Handles I/O errors.
2 System.IndexOutOfRangeException
Handles errors generated when a method refers to an array index out of range.
3 System.ArrayTypeMismatchException
Handles errors generated when type is mismatched with the array type.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
61
4 System.NullReferenceException
Handles errors generated from referencing a null object.
5 System.DivideByZeroException
Handles errors generated from dividing a dividend with zero.
6 System.InvalidCastException
Handles errors generated during typecasting.
7 System.OutOfMemoryException
Handles errors generated from insufficient free memory.
8 System.StackOverflowException
Handles errors generated from stack overflow.
Handling Exceptions
C# provides a structured solution to the exception handling in the form of try and catch blocks. Using
these blocks the core program statements are separated from the error-handling statements.
These error handling blocks are implemented using the try, catch, and finally keywords. Following is an
example of throwing an exception when dividing by zero condition occurs −
using System;
namespace ErrorHandlingApplication {
class DivNumbers {
int result;
DivNumbers() {
result = 0;
}
public void division(int num1, int num2) {
try {
result = num1 / num2;
} catch (DivideByZeroException e) {
Console.WriteLine("Exception caught: {0}", e);
} finally {
Console.WriteLine("Result: {0}", result);
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
62
}
}
static void Main(string[] args) {
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0
Creating User-Defined Exceptions
You can also define your own exception. User-defined exception classes are derived from
the Exception class. The following example demonstrates this −
using System;
namespace UserDefinedException {
class TestTemperature {
static void Main(string[] args) {
Temperature temp = new Temperature();
try {
temp.showTemp();
} catch(TempIsZeroException e) {
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: Exception {
public TempIsZeroException(string message): base(message) {
}
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
63
}
public class Temperature {
int temperature = 0;
public void showTemp() {
if(temperature == 0) {
throw (new TempIsZeroException("Zero Temperature found"));
} else {
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
When the above code is compiled and executed, it produces the following result −
TempIsZeroException: Zero Temperature found
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception class. You
can use a throw statement in the catch block to throw the present object as −
Catch(Exception e) {
...
Throw e
}
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.
Declaring Delegates
Delegate declaration determines the methods that can be referenced by the delegate. A delegate can refer to
a method, which has the same signature as that of the delegate.
For example, consider a delegate −
public delegate int MyDelegate (string s);
The preceding delegate can be used to reference any method that has a single string parameter and returns
an int type variable.
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
64
Syntax for delegate declaration is –
delegate <return type> <delegate-name> <parameter list>
Instantiating Delegates
Once a delegate type is declared, a delegate object must be created with the new keyword and be associated
with a particular method. When creating a delegate, the argument passed to the new expression is written
similar to a method call, but without the arguments to the method. For example :
public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
Following example demonstrates declaration, instantiation, and use of a delegate that can be used to
reference methods that take an integer parameter and returns an integer value.
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl {
class TestDelegate {
static int num = 10;
public static int AddNum(int p) {
num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
65
static void Main(string[] args) {
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Value of Num: 35
Value of Num: 175
Multicasting of a Delegate
Delegate objects can be composed using the "+" operator. A composed delegate calls the two delegates it
was composed from. Only delegates of the same type can be composed. 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. This is called multicasting of a delegate. The following program demonstrates
multicasting of a delegate −
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl {
class TestDelegate {
static int num = 10;
public static int AddNum(int p) {
num += p;
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
66
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
nc += nc2;
//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Value of Num: 75
Using Delegates
The following example demonstrates the use of delegate. The delegate printString can be used to reference
method that takes a string as input and returns nothing.
We use this delegate to call two methods, the first prints the string to the console, and the second one prints
it to a file −
using System;
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
67
using System.IO;
namespace DelegateAppl {
class PrintString {
static FileStream fs;
static StreamWriter sw;
// delegate declaration
public delegate void printString(string s);
// this method prints to the console
public static void WriteToScreen(string str) {
Console.WriteLine("The String is: {0}", str);
}
//this method prints to a file
public static void WriteToFile(string s) {
fs = new FileStream("c:message.txt",
FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
// this method takes the delegate as parameter and uses it to
// call the methods as required
public static void sendString(printString ps) {
ps("Hello World");
}
static void Main(string[] args) {
printString ps1 = new printString(WriteToScreen);
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
68
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
The String is: Hello World
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 −
event BoilerLogHandler BoilerEventLog;
The preceding code defines a delegate named BoilerLogHandler and an event named BoilerEventLog,
which invokes the delegate when it is raised.
Example
using System;
namespace SampleApp {
public delegate string MyDel(string str);
C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI
Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS)
Page
69
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("Tutorials Point");
Console.WriteLine(result);
}
}
}
When the above code is compiled and executed, it produces the following result −
Welcome Tutorials Point

More Related Content

Similar to C# and Dot Net Framework 1st & 2nd Unit.pdf (20)

PDF
dot net unit-1.pdf
Prof. Dr. K. Adisesha
 
PPTX
3. WEB TECHNOLOGIES.pptx B.Pharm sem 2 CAP
Vedika Narvekar
 
PPTX
Chapter1
krobinson937
 
PPTX
Introduction to web designing
Rajat Shah
 
PPTX
1 Intro of web technology and sciences .pptx
angelinjeba6
 
PPTX
Choice of programming language for web developing.
Mohammad Kamrul Hasan
 
PPTX
CLIENT SIDE PROCESSING.pptx
agniva pradhan
 
PDF
web desigining and publishing and easy level
animefun210
 
PPTX
Introduction to Web Development
Parvez Mahbub
 
PPTX
025444215.pptx
RiyaJenner1
 
PPTX
Website/Web Applications / Static vs Dynamic Website / Web Browser /
Sachin Yadav
 
PPT
02 intro
babak mehrabi
 
PPT
Web engineering 2(lect 0)
Roohul Amin
 
DOCX
this a JAVA PROGRAMMING manual file.docx
dhinesh3090
 
PDF
shobhit training report (3) (4).pdf report
poojaranga2911
 
PPTX
Web development revolution
Ahmed El-Zekred
 
PDF
web development
ABHISHEKJHA176786
 
PPTX
25444215.pptx
YashMittal302244
 
PPTX
What Are The Different Types Of Web Technologies.pptx
JuliusECatipon
 
PPTX
WEB DEVELOPMENT.pptx
silvers5
 
dot net unit-1.pdf
Prof. Dr. K. Adisesha
 
3. WEB TECHNOLOGIES.pptx B.Pharm sem 2 CAP
Vedika Narvekar
 
Chapter1
krobinson937
 
Introduction to web designing
Rajat Shah
 
1 Intro of web technology and sciences .pptx
angelinjeba6
 
Choice of programming language for web developing.
Mohammad Kamrul Hasan
 
CLIENT SIDE PROCESSING.pptx
agniva pradhan
 
web desigining and publishing and easy level
animefun210
 
Introduction to Web Development
Parvez Mahbub
 
025444215.pptx
RiyaJenner1
 
Website/Web Applications / Static vs Dynamic Website / Web Browser /
Sachin Yadav
 
02 intro
babak mehrabi
 
Web engineering 2(lect 0)
Roohul Amin
 
this a JAVA PROGRAMMING manual file.docx
dhinesh3090
 
shobhit training report (3) (4).pdf report
poojaranga2911
 
Web development revolution
Ahmed El-Zekred
 
web development
ABHISHEKJHA176786
 
25444215.pptx
YashMittal302244
 
What Are The Different Types Of Web Technologies.pptx
JuliusECatipon
 
WEB DEVELOPMENT.pptx
silvers5
 

More from MohammedAnas871930 (7)

PPTX
Unit-2_chap-4.pptx you from the heart of the
MohammedAnas871930
 
PPTX
Stacks.pptx in software engineering in simple understanding
MohammedAnas871930
 
PPTX
Unit-1_c.pptx you from the heart of the day revision
MohammedAnas871930
 
PPTX
open_source_tools.pptx 4th sem bca......
MohammedAnas871930
 
PPTX
PRESENTATION SKILLS III SEM ENGLISH PPT.pptx
MohammedAnas871930
 
PPTX
Transport layer.pptx
MohammedAnas871930
 
PPTX
Presentation1 Networking.pptx
MohammedAnas871930
 
Unit-2_chap-4.pptx you from the heart of the
MohammedAnas871930
 
Stacks.pptx in software engineering in simple understanding
MohammedAnas871930
 
Unit-1_c.pptx you from the heart of the day revision
MohammedAnas871930
 
open_source_tools.pptx 4th sem bca......
MohammedAnas871930
 
PRESENTATION SKILLS III SEM ENGLISH PPT.pptx
MohammedAnas871930
 
Transport layer.pptx
MohammedAnas871930
 
Presentation1 Networking.pptx
MohammedAnas871930
 
Ad

Recently uploaded (20)

PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Ad

C# and Dot Net Framework 1st & 2nd Unit.pdf

  • 1. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 1 Unit – 01 Introduction to .Net Technologies Introduction to HTML ➢ HTML stands for Hyper Text Markup Language. ➢ HTML was invented by Tim Berners-Lee ➢ HTML is the standard markup language for creating Web pages. ➢ HTML describes the structure of a Web page ➢ HTML consists of a series of elements ➢ HTML elements tell the browser how to display the content ➢ HTML elements label pieces of content such as "this is a heading", "this isa paragraph", "this is a link", etc. ➢ HTML5 described as a new version of HTML. ➢ HTML5 was the successor to previous HTML versions. ➢ HTML is Not Case Sensitive. HTML History Since the early days of the World Wide Web, there have been many versions of HTML: Year Version 1989 Tim Berners-Lee invented www 1991 Tim Berners-Lee invented HTML 1993 Dave Raggett drafted HTML+ 1995 HTML Working Group defined HTML 2.0 1997 HTML 3.2 1999 HTML 4.01 2000 XHTML 1.0 2008 WHATWG HTML5 First Public Draft 2012 WHATWG HTML5 Living Standard 2014 HTML5 2016 HTML 5.1 2017 HTML5.1 2nd Edition
  • 2. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 2 Editors: ➢ Web pages can be created and modified by using professional HTML editors. ➢ For learning HTML, we need to use a simple text editor like Notepad (PC) or TextEdit (Mac). HTML Element ➢ An HTML element is defined by a start tag, some content, and an end tag: o <tagname> Content goes here... </tagname> ➢ The HTML element is everything from the start tag to the end tag: o <h1>My First Heading</h1> o <p>My first paragraph.</p> HTML Attributes ➢ All HTML elements can have attributes. ➢ Attributes provide additional information about elements. ➢ Attributes are always specified in the start tag. ➢ Attributes usually come in name/value pairs like: name="value". HTML Basic Tags HTML Headings: HTML headings are defined with the <h1> to <h6> tags. Ex: o <h1>This is heading 1</h1> o <h2>This is heading 2</h2> o <h3>This is heading 3</h3> HTML Paragraphs: HTML paragraphs are defined with the <p> tag: Ex: <p>This is a paragraph.</p> HTML Links: HTML links are defined with the <a> tag, The “href” attribute specifies the URL ofthe page the link goes to: Ex: <a href="https://www.bbc.edu.in">This is a link</a> HTML Images: ➢ HTML images are defined with the <img> tag. ➢ The source file (src), alternative text (alt), width, and height are provided asattributes: Ex: <img src=" c:picturesa1.jpg” alt=" Picture notfound” width="104" height="142"> Marquee Tags: ➢ The Marquee HTML tag is a non-standard HTML element, which is used toscroll a image or text horizontally or vertically. ➢ In simple words, we can say that it scrolls the image or text up, down, left or rightautomatically. ➢ Marquee tag was first introduced in early versions of Microsoft's Internet Explorer. Ex: <marquee width="100%" direction="right">
  • 3. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 3 This is an example of a right direction marquee... </marquee> The style Attribute The style attribute is used to add styles to an element, such as color, font, size,and more. Ex: <p style="color:red;">This is a red paragraph.</p> The lang Attribute: ➢ You should always include the lang attribute inside the <html> tag, to declare thelanguage of the Web page. ➢ This is meant to assist search engines and browsers. Ex: <html lang="en"> How to View HTML Source Right-click in an HTML page and select "View Page Source" (in Chrome) or "View Source" (in Edge), or similar in other browsers. This will open a windowcontaining the HTML source code of the page. Web Browsers: ➢ The purpose of a web browser (Chrome, Edge, Firefox, and Safari) is to readHTML documents and display them correctly. ➢ A browser does not display the HTML tags, but uses them to determine how to display the document: Scripting Language: A script or scripting language is a computer language thatdoes not need the compilation step and is rather interpreted one by one at runtime. Types of scripting languages: There are two types, they are: 1. Client-side scripting language: A client-side script is a small program (or set of instructions) thatis embedded (or inserted) into a web page. It is processed within the clientbrowser instead of the web server. Ex: JavaScript, VBScript, jQuery, HTML (structure), CSS (Design), etc. Advantages of client-side scripting languages: 1. The client-side scripting language is quite easy to learn and use. It requires minimum programming knowledge or experienced required. 2. The main advantage of client-side scripting is that it is lightweight and relatively easy to implement (syntax not too complex). The editing and executingthe code is fast. 3. Data processing is done on the client side from the server, which makes it easier to scale applications with large numbers of users. Thereby, load on theserver reduces. 4. The client-side data validation can be possible using the client-side scriptinglanguage like JavaScript. 5. The execution of client-side script is more quickly because once the script is downloaded from the server; it is executed by the browser directly on the user’scomputer. 6. Mathematical assessment is also possible using client-side scripting. 7. The client-side programming helps to perform the complex tasks in relativelyfew steps. 8. Script code only executed by the browser without connecting the server.
  • 4. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 4 9. It takes too less time to execute script code. 10. Browser respond immediately when user presses any key, mouse movement,clicks, etc. Disadvantages of client-side scripting languages: There are certain disadvantages of client-side scripting that are as follows: 1. The main disadvantage of client-side scripting is that it is unsecure because thecode is sent as is to the client and, therefore, visible to it if the client looks at the sources of his web page. In short, code is usually visible. 2. Client-side programming cannot be used if we need to access databases orneeds to transmit sensitive data over the internet. 3. There is no guarantee that user has enabled JavaScript on his computer’sbrowser. Therefore, any required functionality must be loaded on the serverdespite the possibility that it could be offloaded. 4. The smooth running of the script (or program) depends entirely on the client’sbrowser, its configuration, and security level. 5. The web application based on the heavy JavaScript can be complicated todebug and maintain. 2. Server-side scripting language: A server-side script is a program that is executed on the server side when the user request information. The script do not download at the client side. OR a server-side script is executed by the web browser. Ex: PHP, Python, Ruby, ASP.Net, Perl, etc. Advantages of server-side scripting: 1. Server side scripting executes scripts on server,it reduces the load on user’scomputer. 2. Server-side scripting is used to create database web application.Or 3. It deals with the database. 4. Server-side scripts are used to hide scripts from the users. 5. Server scripts are used to generate dynamic website easily in which admin canalter the code at any time. 6. Server scripts do not depend on browser therefore; we do not need to worryabout version of browsers. 7. Server-side scripts are used to perform complex tasks. 8. It is easy to learn and use. 9. Server-side script cannot be disabled at the client side. 10. Server-side scripting is more secure than client-side scripting.10.It provides code reusability. Disadvantages of server-side scripting: 1. Web Server scripts are difficult to debug. 2. We need a high configuration server to use server-side scripting. 3. Server-side scripting is slower than client-side scripting. 4. It takes more time to execute scripts than client-side scripting.
  • 5. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 5 Difference between Client-Side V/S Server-Side Client side Client Side 1. It involves web browser. 2. All the code resides on a web browser. 3. Cannot connect to the database. 4. Response is fast. 5. It is less secure. 6. Use to develop frontend applications. Ex: Users form etc. Server Side 1. It involves web server. 2. User web browser makes a request to the server. 3. Can connect to the database. 4. Response is slow. 5. It is more secure. 6. Use to develop backend applications. Ex: Dynamic Websites etc. Client-side scripting technologies: JavaScript ➢ JavaScript (JS) is a lightweight, interpreted, or just-in-time compiledprogramming language with first-class functions. ➢ It is most well known as the scripting language for Web pages. ➢ JavaScript is very easy to implement because it is integrated with HTML.It is open and cross- platform. ➢ As of 2022, 98% of websites use JavaScript on the client side for webpage behavior. All major web browsers have a dedicated JavaScriptengine to execute the code on users' devices. Ex: <script language = "javascript" type = "text/javascript"> <!-- document.write("Hello World!") //--> </script> VBScript ➢ Microsoft develops VBScript (visual Basic Script) with the intention ofdeveloping dynamic web pages. ➢ It is client-side scripting language like JavaScript. ➢ VBScript is a light version of Microsoft Visual Basic. The syntax of VBScript is very similar to that of Visual Basic. If you want your webpageto be more lively and interactive, then you can incorporate VBScript in your code. ➢ VBScript is just a scripting language. So,it cannot run its code on its own.It needs a bigger programming language to host it. Ex: <script type="text/vbscript"> document.write("Yes!!! I have started learning VBScript.") </script>
  • 6. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 6 AJAX ➢ It stands for Asynchronous JavaScript and XML. ➢ AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script. jQuery ➢ Good for highly interactive web applications. ➢ Open source and free to use. ➢ Powerful theme mechanism. ➢ Stable and maintenance friendly. ➢ Extensive browser support.
  • 7. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 7 Unit-2 Introduction to C# Overview of C# ➢ C# is pronounced as "C-Sharp". ➢ It was created by Microsoft Corporation and led by Anders Hejlsberg,which runs on the .NET Framework. ➢ It is an object-oriented programming language, which provides all the oopconcepts to the user. ➢ C# has roots from the C family, and the language is close to other popularlanguages like C++ and Java. ➢ The first version of C# was released in the year 2002. The latest version of ➢ C# 11, was released in November 2022. ➢ It is easy to learn and use. ➢ C# provides reusability. C# is used for: ➢ Mobile applications ➢ Desktop applications ➢ Web applications ➢ Web services ➢ Web sites ➢ Games ➢ VR ➢ Database applications, etc. Why Use C#? • It is one of the most popular programming languages in the world. • It is easy to learn and to use. • It has a huge community support. • C# is an object-oriented language, which gives a clear structure to programs and allows code to be reused, lowering development costs. • As C# is close to C, C++ and Java, it makes it easy for programmers toswitch to C# or vice versa. Literals: The fixed values are called literals. The constants refer to fixed values that the program may
  • 8. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 8 not alter during its execution. Constants can be of anyof the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. Integer Literals An integer literal can be a decimal, or hexadecimal constant. A prefix specifies thebase or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and canbe in any order. Here are some examples of integer literals: Following are other examples of various types of Integer literals: Floating-point Literals A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. Here are some examples of floating-point literals: Character Literals ▪ Character literals are enclosed in single quotes. ▪ For example, 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (such as 'x'). Ex: char ch = 'a'; Escape Sequence: Every escape character can be an literal. Ex: char ch = 'n'; Unicode Representation: We can specify char literals in Unicode representation ‘uxxxx’. Here xxxx represents 4 hexadecimal numbers. Ex: char ch = 'u0061';// Here /u0061 represent a. String Literals ▪ String literals or constants are enclosed in double quotes " " or with @"". ▪ A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. Ex: String s1=” Hi….. Welcome to Ballari”; String s2 =@”BCA DEPARTMENT”; 212 /* Legal */ 215u /*Legal*/ 0xFeeL /* Legal */ 85 /* decimal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */ 3.14159 /* Legal */ 314159E-5F /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */
  • 9. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 9 Boolean Literals: Only two values are allowed for Boolean literals i.e., true and false. Ex: bool b = true; bool c = false; C# Variables: ➢ Variables are containers for storing data values. ➢ In C#, there are different types of variables (defined with different keywords), for example: ▪ int - stores integers (whole numbers), without decimals, such as 123 or - 123 ▪ double - stores floating point numbers, with decimals, such as 19.99 or - 19.99 ▪ char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes ▪ String - stores text, such as "Hello World". String values are surrounded by double quotes ▪ bool - stores values with two states: true or false Declaring (Creating) Variables To create a variable, you must specify the type and assign it a value: Syntax: type variableName = value; Where type is a C# type (such as int or string), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable. Examples: ▪ int myNum = 5; ▪ double myDoubleNum = 5.99D; ▪ char myLetter = 'D'; ▪ bool myBool = true; ▪ string myText = "Hello"; Constants: ➢ If you don't want others (or yourself) to overwrite existing values, you can add the const keyword in front of the variable type. ➢ This will declare the variable as "constant", which means unchangeable and read-only: Example: const int myNum = 15; myNum = 20; // error
  • 10. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 10 C# Data Types A data type specifies the type of data that a variable can store such as integer, floating, character etc. Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types. Data types in C# is mainly divided into three categories ▪ Value Data Types ▪ Reference Data Types ▪ Pointer Data Type 1. Value Data Types: In C#, the Value Data Types will directly store the variable value in memory and it will also accept both signed and unsigned literals. The derived class for these data types are System.ValueType. Following is different Value Data Types in C# programming language Signed & Unsigned Integral Types: There are 8 integral types which provide support for 8-bit, 16-bit, 32- bit, and 64-bit values in signed or unsigned form. Alias Type Name Type Size(bits) Range Default Value Sbyte System.Sbyte signed integer 8 -128 to 127 0 Short System.Int16 signed integer 16 -32768 to 32767 0 Int System.Int32 signed integer 32 -231 to 231 -1 0 Long System.Int64 signed integer 64 -263 to 263 -1 0L Byte System.byte unsigned integer 8 0 to 255 0 Ushort System.UInt16 unsigned integer 16 0 to 65535 0 Uint System.UInt32 unsigned integer 32 0 to 232 0 Ulong System.UInt64 unsigned integer 64 0 to 263 0
  • 11. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 11 Floating Point Types: There are 2 floating point data types which contain the decimal point. Float: ▪ It is 32-bit single-precision floating point type. ▪ It has 7-digit Precision. ▪ To initialize a float variable, use the suffix f or F. ▪ Like, float x = 3.5F; ▪ If the suffix F or f will not use then it is treated as double. Double: ▪ It is 64-bit double-precision floating point type. ▪ It has 14–15-digit Precision. ▪ To initialize a double variable, use the suffix d or D. ▪ But it is not mandatory to use suffix because by default floating data types are the double type. Alias Type name Size(bits) Range (aprox) Default Value float System.Single 32 ±1.5 × 10-45 to ±3.4 × 1038 0.0F double System.Double 64 ±5.0 × 10-324 to ±1.7 × 10308 0.0D Decimal Types: ▪ The decimal type is a 128-bit data type suitable for financial and monetary calculations. ▪ It has 28–29-digit Precision. ▪ To initialize a decimal variable, use the suffix m or M. ▪ Like as, decimal x = 300.5m; ▪ If the suffix m or M will not use then it is treated as double. Alias Type name Size(bits) Range (aprox) Default value decimal System.Decimal 128 ±1.0 × 10-28 to ±7.9228 × 1028 0.0M Character Types: The character types represent a UTF-16 code unit or represents the 16-bit Unicode character. Alias Type name Size In(Bits) Range Default value char System.Char 16 U +0000 to U +ffff ‘0’ 2. Reference Data Types: The Reference Data Types will contain a memory address of variable value because the reference types won’t store the variable value directly in memory. The built-in reference types are string, object. String: It represents a sequence of Unicode characters and its type name is System.String. So, string and String are equivalent. Example: ▪ string s1 = "hello"; // creating through string keyword ▪ String s2 = "welcome"; // creating through String class Object: ▪ In C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. ▪ So basically, it is the base class for all the data types in C#. ▪ Before assigning values, it needs type conversion. ▪ When a variable of a value type is converted to object, it’s called boxing. ▪ When a variable of type object is converted to a value type, it’s called unboxing. ▪ Its type name is System.Object.
  • 12. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 12 3. Pointer Data Type: ▪ The Pointer Data Types will contain a memory address of the variable value. ▪ To get the pointer details we have a two symbols ampersand (&) and asterisk (*). ▪ ampersand (&): It is Known as Address Operator. ▪ It is used to determine the address of a variable. ▪ asterisk (*): It also known as Indirection Operator. ▪ It is used to access the value of an address. Operators ▪ Operators are the foundation of any programming language. ▪ Thus, the functionality of C# language is incomplete without the use of operators. ▪ Operators allow us to perform different kinds of operations on operands. ▪ In C#, operators Can be categorized based upon their different functionality: • Arithmetic Operators • Relational Operators • Logical Operators • Bitwise Operators • Assignment Operators • Conditional Operator ▪ In C#, Operators can also categorize based upon Number of Operands: • Unary Operator: Operator that takes one operand to perform the operation. • Binary Operator: Operator that takes two operands to perform the operation. • Ternary Operator: Operator that takes three operands to perform the operation. Arithmetic Operators ▪ These are used to perform arithmetic/mathematical operations on operands. ▪ The Binary Operators falling in this category are: • Addition: The ‘+’ operator adds two operands. For example, x+y. • Subtraction: The ‘- ‘operator subtracts two operands. For example, x-y. • Multiplication: The ‘*’ operator multiplies two operands. For example, x*y. • Division: The ‘/’ operator divides the first operand by the second. For example, x/y. • Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second. For example, x%y. // C# program to demonstrate the working of Binary Arithmetic Operators using System; namespace Arithmetic { class GFG { // Main Function static void Main (string [] args) { int result; int x = 10, y = 5; // Addition result = (x + y); Console.WriteLine("Addition Operator: " + result); // Subtraction result = (x - y);
  • 13. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 13 Console.WriteLine("Subtraction Operator: " + result); // Multiplication result = (x * y); Console.WriteLine("Multiplication Operator: "+ result); // Division result = (x / y); Console.WriteLine("Division Operator: " + result); // Modulo result = (x % y); Console.WriteLine("Modulo Operator: " + result); } } } The ones falling into the category of Unary Operators are: Increment: ▪ The ‘++’ operator is used to increment the value of an integer. ▪ When placed before the variable name (also called pre-increment operator), its value is incremented instantly. For example, ++x. ▪ And when it is placed after the variable name (also called post-increment operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x++. Decrement: ▪ The ‘– ‘operator is used to decrement the value of an integer. ▪ When placed before the variable name (also called pre-decrement operator), its value is decremented instantly. For example, –x. ▪ And when it is placed after the variable name (also called post-decrement operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x–. Relational Operators: ▪ Relational operators are used for comparison of two values. ▪ Let’s see them one by one: • ‘=='(Equal To) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise, it returns false. For example, 5==5 will return true. • ‘! ='(Not Equal To) operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise, it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5! =5 will return false. • ‘>'(Greater Than) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise, it returns false. For example, 6>5 will return true. • ‘< ‘(Less Than) operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise, it returns false. For example, 6<5 will return false. • ‘>='(Greater Than Equal To) operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise, it returns false. For example, 5>=5 will return true.
  • 14. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 14 • ‘<='(Less Than Equal To) operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise, it returns false. For example, 5<=5 will also return true. // C# program to demonstrate the working // of Relational Operators using System; namespace Relational { class demo { // Main Function static void Main(string[] args) { bool result; int x = 5, y = 10; // Equal to Operator result = (x == y); Console.WriteLine("Equal to Operator: " + result); // Greater than Operator result = (x > y); Console.WriteLine("Greater than Operator: " + result); // Less than Operator result = (x < y); Console.WriteLine("Less than Operator: " + result); // Greater than Equal to Operator result = (x >= y); Console.WriteLine("Greater than or Equal to: "+ result); // Less than Equal to Operator result = (x <= y); Console.WriteLine("Lesser than or Equal to: "+ result); // Not Equal To Operator result = (x != y); Console.WriteLine("Not Equal to Operator: " + result); } } } Logical Operators: They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below: • Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are satisfied. Otherwise, it returns false. For example, a && b returns true when both a and b are true (i.e., non-zero). • Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise, it returns false. For example, a || b returns true if one of a or b is true (i.e., non-zero). Of course, it returns true when both a and b are true.
  • 15. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 15 • Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise, it returns false. For example:! a returns true if a is false, i.e. when a=0. Example: // C# program to demonstrate the working // of Logical Operators using System; namespace Logical { class demo { // Main Function static void Main(string[] args) { bool a = true,b = false, result; // AND operator result = a && b; Console.WriteLine("AND Operator: " + result); // OR operator result = a || b; Console.WriteLine("OR Operator: " + result); // NOT operator result = !a; Console.WriteLine("NOT Operator: " + result); } } } Bitwise Operators ▪ In C#, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations. Following are the bitwise operators: • & (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. • | (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1. • ^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. • << (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift. • >> (right shift) Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift. Example: // C# program to demonstrate the working // of Bitwise Operators using System; namespace Bitwise { class demo { // Main Function
  • 16. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 16 static void Main(string[] args) { int x = 5, y = 10, result; // Bitwise AND Operator result = x & y; Console.WriteLine("Bitwise AND: " + result); // Bitwise OR Operator result = x | y; Console.WriteLine("Bitwise OR: " + result); // Bitwise XOR Operator result = x ^ y; Console.WriteLine("Bitwise XOR: " + result); // Bitwise AND Operator result = ~x; Console.WriteLine("Bitwise Complement: " + result); // Bitwise LEFT SHIFT Operator result = x << 2; Console.WriteLine("Bitwise Left Shift: " + result); // Bitwise RIGHT SHIFT Operator result = x >> 2; Console.WriteLine("Bitwise Right Shift: " + result); } } } Assignment Operators ▪ Assignment operators are used to assigning a value to a variable. ▪ The left side operand of the assignment operator is a variable and right-side operand of the assignment operator is a value. ▪ The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. ▪ Different types of assignment operators are shown below: • “=” (Simple Assignment): This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: o a = 10; o b = 20; o ch = 'y'; • “+=” (Add Assignment): This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example: o (a += b) can be written as (a = a + b) o If initially value stored in a is 5. Then (a += 6) = 11. • “-=” (Subtract Assignment): This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and
  • 17. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 17 then assigns the result to the variable on the left. Example: o (a -= b) can be written as (a = a - b) o If initially value stored in a is 8. Then (a -= 6) = 2. • “*=” (Multiply Assignment): This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example: o (a *= b) can be written as (a = a * b) o If initially value stored in a is 5. Then (a *= 6) = 30. • “/=” (Division Assignment): This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example: o (a /= b) can be written as (a = a / b) o If initially value stored in a is 6. Then (a /= 2) = 3. • “%=” (Modulus Assignment): This operator is combination of ‘%’ and ‘=’ operators. This operator first modulo the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example: o (a %= b) can be written as (a = a % b) o If initially value stored in a is 6. Then (a %= 2) = 0. • “<<=” (Left Shift Assignment): This operator is combination of ‘<< ‘and ‘=’ operators. This operator first Left shift the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example: o (a <<= 2) can be written as (a = a << 2) o If initially value stored in a is 6. Then (a <<= 2) = 24. • “>>=” (Right Shift Assignment): This operator is combination of ‘>>’ and ‘=’ operators. This operator first Right shift the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example: o (a >>= 2) can be written as (a = a >> 2) o If initially value stored in a is 6. Then (a >>= 2) = 1. • “&=” (Bitwise AND Assignment): This operator is combination of ‘&’ and ‘=’ operators. This operator first “Bitwise AND” the current value of the variable on the left by the value on the right and then assigns the result to the variable on the left. Example: o (a &= 2) can be written as (a = a & 2) o If initially value stored in a is 6. Then (a &= 2) = 2. • “^=” (Bitwise Exclusive OR): This operator is combination of ‘^’ and ‘=’ operators. This operator first “Bitwise Exclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example: o (a ^= 2) can be written as (a = a ^ 2) o If initially value stored in a is 6. Then (a ^= 2) = 4. • “|=” (Bitwise Inclusive OR): This operator is combination of ‘|’ and ‘=’ operators. This operator first “Bitwise Inclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example: o (a |= 2) can be written as (a = a | 2)
  • 18. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 18 o If initially, value stored in a is 6. Then (a |= 2) = 6. Example: // C# program to demonstrate the working // of Assignment Operators using System; namespace Assignment { class demo { // Main Function static void Main(string[] args) { // initialize variable x // using Simple Assignment // Operator "=" int x = 15; // it means x = x + 10 x += 10; Console.WriteLine("Add Assignment Operator: " + x); // initialize variable x again x = 20; // it means x = x - 5 x -= 5; Console.WriteLine("Subtract Assignment Operator: " + x); // initialize variable x again x = 15; // it means x = x * 5 x *= 5; Console.WriteLine("Multiply Assignment Operator: " + x); // initialize variable x again x = 25; // it means x = x / 5 x /= 5; Console.WriteLine("Division Assignment Operator: " + x); // initialize variable x again x = 25; // it means x = x % 5 x %= 5; Console.WriteLine("Modulo Assignment Operator: " + x); // initialize variable x again x = 8;
  • 19. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 19 // it means x = x << 2 x <<= 2; Console.WriteLine("Left Shift Assignment Operator: " + x); // initialize variable x again x = 8; // it means x = x >> 2 x >>= 2; Console.WriteLine("Right Shift Assignment Operator: " + x); // initialize variable x again x = 12; // it means x = x >> 4 x &= 4; Console.WriteLine("Bitwise AND Assignment Operator: " + x); // initialize variable x again x = 12; // it means x = x >> 4 x ^= 4; Console.WriteLine("Bitwise Exclusive OR Assignment Operator: " + x); // initialize variable x again x = 12; // it means x = x >> 4 x |= 4; Console.WriteLine("Bitwise Inclusive OR Assignment Operator: " + x); } } } Conditional Operator: ➢ It is ternary operator which is a shorthand version of if-else statement. ➢ It has three operands and hence the name ternary. ➢ It will return one of two values depending on the value of a Boolean expression. Syntax: condition ? first_expression : second_expression; Explanation: ▪ condition: It must be evaluated to true or false. ▪ If the condition is true. ▪ first_expression is evaluated and becomes the result. ▪ If the condition is false, ▪ second_expression is evaluated and becomes the result. Example: // C# program to demonstrate the working // of Conditional Operator using System; namespace Conditional {
  • 20. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 20 class demo { // Main Function static void Main(string[] args) { int x = 5, y = 10, result; // To find which value is greater // Using Conditional Operator result = x > y ? x : y; // To display the result Console.WriteLine("Result: " + result); // To find which value is greater // Using Conditional Operator result = x < y ? x : y; // To display the result Console.WriteLine("Result: " + result); } }} Decision Making: in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. The conditional statements of C#: ➢ if ➢ if-else ➢ if-else-if ➢ Nested if ➢ Switch ➢ Nested switch if Statement: ➢ The if statement checks the given condition. ➢ If the condition evaluates to be true then the block of code/statements will execute otherwise not. Syntax: if(condition) { //code to be executed } Note: If the curly brackets { } are not used with if statements than the statement just next to it is only considered associated with the if statement. Example: if (condition) statement 1; statement 2; In this example, only statement 1 is considered to be associated with the if statement.
  • 21. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 21 Flowchart: Example: // C# program to illustrate if statement using System; public class demo { public static void Main(string[] args) { string name = "smdc"; if (name == "smdc") { Console.WriteLine("smdc college"); } } } Output: Smdc college ➢ if else Statement The if statement evaluates the code if the condition is true but what if the condition is not true, here comes the else statement. ➢ It tells the code what to do when the if condition is false. ➢ Syntax: if(condition) { // code if condition is true } else { // code if condition is false } Flowchart:
  • 22. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 22 Example: // C# program to illustrate // if-else statement using System; public class demo { public static void Main(string[] args) { string name = "smdc"; if (name == "smdc") { Console.WriteLine("Smdc College"); } else { Console.WriteLine("smdc"); } }} Output: Smdc College if – else – if/else_if ladder Statement ➢ The if-else-if ladder statement executes one condition from multiple statements. ➢ The execution starts from top and checked for each if condition. ➢ The statement of if block will be executed which evaluates to be true. ➢ If none of the if condition evaluates to be true then the last else block is evaluated. Syntax: if(condition1) { // code to be executed if condition1 is true } else if(condition2) { // code to be executed if condition2 is true } else if(condition3) { // code to be executed if condition3 is true } ... else { // code to be executed if all the conditions are false } Example: Flowchart: // C# program to illustrate // if-else-if ladder using System; class demo { public static void Main(String[] args) {
  • 23. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 23 int i = 20; if (i == 10) Console.WriteLine("i is 10"); else if (i == 15) Console.WriteLine("i is 15"); else if (i == 20) Console.WriteLine("i is 20"); else Console.WriteLine("i is not present"); } } Output: i is 20 Nested – If Statement ➢ if statement inside an if statement is known as nested if. ➢ if statement in this case is the target of another if or else statement. ➢ When more than one condition needs to be true and one of the condition is the sub-condition of parent condition, nested if can be used. Syntax: if (condition1) { // code to be executed // if condition2 is true if (condition2) { // code to be executed // if condition2 is true } } Flowchart: Example: // C# program to illustrate // nested-if statement using System; class demo { public static void Main(String[] args) { int i = 10; if (i == 10) { // Nested - if statement // Will only be executed if statement // above it is true
  • 24. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 24 if (i < 12) Console.WriteLine("i is smaller than 12 too"); else Console.WriteLine("i is greater than 15"); } } } Output: i is smaller than 12 too Switch Statement Flow Diagram of Switch – case: ➢ Switch statement is an alternative to long if-else-if ladders. ➢ The expression is checked for different cases and the one match is executed. ➢ Break statement is used to move out of the switch. ➢ If the break is not used, the control will flow to all cases below it until break is found or switch comes to an end. ➢ There is default case (optional) at the end of switch, if none of the case matches then default case is executed. Syntax: switch (expression) { case value1: // statement sequence break; case value2: // statement sequence break; . . . case valueN: // statement sequence break; default: // default statement sequence } Example: // C# example for switch case using System; public class demo
  • 25. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 25 { public static void Main(String[] args) { int number = 30; switch(number) { case 10: Console.WriteLine("case 10"); break; case 20: Console.WriteLine("case 20"); break; case 30: Console.WriteLine("case 30"); break; default: Console.WriteLine("None matches"); break; } } } Output: case 30 Nested switch ➢ Nested Switch case are allowed in C#. ➢ In this case, switch is present inside other switch case. ➢ Inner switch is present in one of the cases in parent switch. Example: // C# example for nested switch case using System; public class demo { public static void Main(String[] args) { int j = 5; switch (j) { case 5: Console.WriteLine(5); switch (j - 1) { case 4: Console.WriteLine(4); switch (j - 2) { case 3: Console.WriteLine(3); break; } break; } break; case 10: Console.WriteLine(10); break; case 15: Console.WriteLine(15); break; default: Console.WriteLine(100); break; }
  • 26. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 26 } } Output: 5 4 3 Looping Statements ➢ Looping in a programming language is a way to execute a statement or a set of statements multiple times depending on the result of the condition to be evaluated to execute statements. ➢ The result condition should be true to execute statements within loops. ➢ Loops are mainly divided into two categories: Entry Controlled Loops: ➢ The loops in which condition to be tested is present in beginning of loop body are known as Entry Controlled Loops. ➢ while loop and for loop are entry- controlled loops. 1. while loop: The test condition is given in the beginning of the loop and all statements are executed till the given boolean condition satisfies when the condition becomes false, the control will be out from the while loop. Syntax: while (boolean condition) { loop statements... } Example: Flowchart: // C# program to illustrate while loop using System; class whileLoopDemo { public static void Main() { int x = 1; // Exit when x becomes greater than 4 while (x <= 4) { Console.WriteLine("smdc college"); // Increment the value of x for // next iteration x++;
  • 27. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 27 } } } Output: Smdc college Smdc college Smdc college Smdc college 2. for loop ➢ for loop has similar functionality as while loop but with different syntax. ➢ for loops are preferred when the number of times loop statements are to be executed is known beforehand. ➢ The loop variable initialization, condition to be tested, and increment/decrement of the loop variable is done in one line in for loop thereby providing a shorter, easy to debug structure of looping. Syntax: for (loop variable initialization; testing condition; increment / decrement) { // statements to be executed } 1. Initialization of loop variable: Th expression / variable controlling the loop is initialized here. It is the starting point of for loop. An already declared variable can be used or a variable can be declared, local to loop only. 3. Testing Condition: The testing condition to execute statements of loop. It is used for testing the exit condition for a loop. It must return a boolean value true or false. When the condition became false the control will be out from the loop and for loop ends. Flowchart: 2. Increment / Decrement: The loop variable is incremented/decremented according to the requirement and the control then shifts to the testing condition again. Note: Initialization part is evaluated only once when the for loop starts. Example: // C# program to illustrate for loop. using System; class forLoopDemo { public static void Main() { // for loop begins when x=1 // and runs till x <=4 for (int x = 1; x <= 4; x++)
  • 28. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 28 Console.WriteLine("smdc college"); } } Exit Controlled Loops: ➢ The loops in which the testing condition is present at the end of loop body are termed as Exit Controlled Loops. ➢ do-while is an exit-controlled loop. Note: In Exit Controlled Loops, loop body will be evaluated for at-least one time as the testing condition is present at the end of loop body. 3. do-while loop do while loop is similar to while loop with the only difference that it checks the condition after executing the statements, i.e it will execute the loop body one time for sure because it checks the condition after executing the statements. Syntax: do { statements.. }while (condition); Example: Flowchart: // C# program to illustrate do-while loop using System; class dowhileloopDemo { public static void Main() { int x = 21; do { // The line will be printed even // if the condition is false Console.WriteLine("smdc college"); x++; } while (x < 20); } } Output: Smdc college 4. Infinite Loops: The loops in which the test condition does not evaluate false ever tend to execute statements
  • 29. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 29 forever until an external force is used to end it and thus, they are known as infinite loops. Example: // C# program to demonstrate infinite loop using System; class infiniteLoop { public static void Main() { // The statement will be printed // infinite times for(;;) Console.WriteLine("This is printed infinite times"); } } Output: This is printed infinite times This is printed infinite times This is printed infinite times This is printed infinite times This is printed infinite times This is printed infinite times This is printed infinite times .......... 5. Nested Loops: When loops are present inside the other loops, it is known as nested loops. Example: // C# program to demonstrate nested loops using System; class nestedLoops { public static void Main() { // loop within loop printing smdc college for(int i = 2; i < 3; i++) for(int j = 1; j < i; j++) Console.WriteLine("smdc college"); } } Output: Smdc college Continue Statement: Continue statement is used to skip over the execution part of loop on a certain condition and move the flow to next updation part. Flowchart: Example:
  • 30. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 30 // C# program to demonstrate continue statement using System; class demoContinue { public static void Main() { // because of continue statement for(int i = 1; i < 3; i++) { if(i == 2) continue; Console.WriteLine("smdc college"); } } } Output: Smdc college Jump Statements (Break, Continue, Goto, Return and Throw) In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. There are five keywords in the Jump Statements: ➢ break ➢ continue ➢ goto ➢ return ➢ throw break statement: The break statement is used to terminate the loop or statement in which it present. After that, the control will pass to the statements that present after the break statement, if available. If the break statement presents in the nested loop, then it terminates only those loops which contains break statement.
  • 31. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 31 Flowchart: continue statement: This statement is used to skip over the execution part of the loop on a certain condition. After that, it transfers the control to the beginning of the loop. Basically, it skips its following statements and continues with the next iteration of the loop. Flowchart: Example: // C# program to illustrate the // use of continue statement using System; class demo { // Main Method public static void Main() { // This will skip 4 to print for (int i = 1; i <= 10; i++) { // if the value of i becomes 4 then // it will skip 4 and send the // transfer to the for loop and // continue with 5 if (i == 4) continue; Console.WriteLine(i); } } } Output: 1 2 3 5 6
  • 32. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 32 7 8 9 10 goto statement: This statement is used to transfer control to the labeled statement in the program. The label is the valid identifier and placed just before the statement from where the control is transferred. Example: Flowchart: // C# program to illustrate the // use of goto statement using System; class demo { // Main Method static public void Main() { int number = 20; switch (number) { case 5: Console.WriteLine("case 5"); break; case 10: Console.WriteLine("case 10"); break; case 20: Console.WriteLine("case 20"); // goto statement transfer // the control to case 5 goto case 5; default: Console.WriteLine("No match found"); break; } } } Output: case 20 case 5 return statement: This statement terminates the execution of the method and returns the control to the calling method. It returns an optional value. If the type of method is void, then the return statement can be excluded. Example:
  • 33. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 33 // C# program to illustrate the // use of return statement using System; class demo { // creating simple addition function static int Addition(int a) { // add two value and // return the result of addition int add = a + a; // using return statement return add; } // Main Method static public void Main() { int number = 2; // calling addition function int result = Addition(number); Console.WriteLine("The addition is {0}", result); } } Output: The addition is 4 throw statement: This is used to create an object of any valid exception class with the help of new keyword manually. The valid exception must be derived from the Exception class. Example: // C# Program to illustrate the use // of throw keyword using System; class demo { // taking null in the string static string sub = null; // method to display subject name static void displaysubject(string sub1) { if (sub1 == null) throw new NullReferenceException("Exception Message"); } // Main Method static void Main(string[] args) { // using try catch block to // handle the Exception
  • 34. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 34 try { // calling the static method displaysubject(sub); } catch(Exception exp) { Console.WriteLine(exp.Message ); } } } Output: Exception Message Methods ➢ A method is a group of statements that together perform a task. ➢ Every C# program has at least one class with a method named Main. ➢ To use a method, you need to − ▪ Define the method ▪ Call the method Defining Methods in C# ➢ When you define a method, you basically declare the elements of its structure. ➢ The syntax for defining a method in C# is as follows − <Access Specifier> <Return Type> <Method Name>(Parameter List) { Method Body } Following are the various elements of a method − ➢ Access Specifier − This determines the visibility of a variable or a method from another class. ➢ Return type − A method may return a value. The return type is the data type of the value the method returns. ➢ If the method is not returning any values, then the return type is void. ▪ Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class. ▪ Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. ▪ Method body − This contains the set of instructions needed to complete the required activity. Example: Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two. It has public access specifier, so it can be accessed from outside the class using an instance of the class. class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */
  • 35. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 35 int result; if (num1 > num2) result = num1; else result = num2; return result; } ... } Calling Methods in C# ➢ You can call a method using the name of the method. The following example illustrates this – Example: using System; namespace CalculatorApplication { class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } static void Main(string[] args) { /* local variable definition */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //calling the FindMax method ret = n.FindMax(a, b); Console.WriteLine("Max value is : {0}", ret ); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Max value is: 200 You can also call public method from other classes by using the instance of the class. For example, the method FindMax belongs to the NumberManipulator class, you can call it from another class Test. Example:
  • 36. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 36 using System; namespace CalculatorApplication { class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if(num1 > num2) result = num1; else result = num2; return result; } } class Test { static void Main(string[] args) { /* local variable definition */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //calling the FindMax method ret = n.FindMax(a, b); Console.WriteLine("Max value is : {0}", ret ); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Max value is : 200 Recursive Method Call ➢ A method can call itself. This is known as recursion. ➢ Following is an example that calculates factorial for a given number using a recursive function − using System; namespace CalculatorApplication { class NumberManipulator {
  • 37. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 37 public int factorial(int num) { /* local variable declaration */ int result; if (num == 1) { return 1; } else { result = factorial(num - 1) * num; return result; } } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); //calling the factorial method {0}", n.factorial(6)); Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7)); Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8)); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result – Factorial of 6 is: 720 Factorial of 7 is: 5040 Factorial of 8 is: 40320 Passing Parameters to a Method ➢ When method with parameters is called, you need to pass the parameters to the method. ➢ There are three ways that parameters can be passed to a method − Sl.No Mechanism & Description 1 Value parameters This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. 2 Reference parameters This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument. 3 Output parameters This method helps in returning more than one value. String Operations: ➢ C# string provides various methods to perform different operations on strings. ➢ We will look into some of the commonly used string operations. 1. Get the Length of a string To find the length of a string, we use the Length property. For example,
  • 38. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 38 using System; namespace CsharpString { class Test { public static void Main(string [] args) { // create string string str = "C# Programming"; Console.WriteLine("string: " + str); // get length of str int length = str.Length; Console.WriteLine("Length: "+ length); Console.ReadLine(); } } } Output: string: C# Programming Length: 14 In the above example, the Length property calculates the total number of characters in the string and returns it. 2. Join two strings in C# We can join two strings in C# using the Concat() method. For example, using System; namespace CsharpString { class Test { public static void Main(string [] args) { // create string string str1 = "C# "; Console.WriteLine("string str1: " + str1); // create string string str2 = "Programming"; Console.WriteLine("string str2: " + str2); // join two strings string joinedString = string.Concat(str1, str2); Console.WriteLine("Joined string: " + joinedString); Console.ReadLine(); } } } Output: string str1: C#
  • 39. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 39 string str2: Programming Joined string: C# Programming • In the above example, we have created two strings named str1 and str2. • Notice the statement, string joinedString = string.Concat(str1, str2); • Here, the Concat() method joins str1 and str2 and assigns it to the joinedString variable. • We can also join two strings using the + operator in C#. 3. C# compare two strings ➢ In C#, we can make comparisons between two strings using the Equals() method. ➢ The Equals() method checks if two strings are equal or not. For example, using System; namespace CsharpString { class Test { public static void Main(string [] args) { // create string string str1 = "C# Programming"; string str2 = "C# Programming"; string str3 = "Programiz"; // compare str1 and str2 Boolean result1 = str1.Equals(str2); Console.WriteLine("string str1 and str2 are equal: " + result1); //compare str1 and str3 Boolean result2 = str1.Equals(str3); Console.WriteLine("string str1 and str3 are equal: " + result2); Console.ReadLine(); } } } Output: string str1 and str2 are equal: True string str1 and str3 are equal: False In the above example, we have created 3 strings named str1, str2, and str3. Here, we are using the Equals() method to check if one string is equal to another. Immutability of String Objects ➢ In C#, strings are immutable. ➢ This means, once we create a string, we cannot change that string. To understand it, consider an example: // create string string str = "Hello ";
  • 40. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 40 Here, we have created a string variable named str. The variable holds the string "Hello ". Now suppose we want to change the string str. // add another string "World" // to the previous string example str = string.Concat(str, "World"); Here, we are using the Concat() method to add the string "World" to the previous string str. But how are we able to modify the string when they are immutable? Let's see what has happened here, 1. C# takes the value of the string "Hello ". 2. Creates a new string by adding "World" to the string "Hello ". 3. Creates a new string object, gives it a value "Hello World", and stores it in str. 4. The original string, "Hello ", that was assigned to str is released for garbage collection because no other variable holds a reference to it. String Escape Sequences ➢ The escape character is used to escape some of the characters present inside a string. ➢ In other words, we use escape sequences to insert special characters inside the string. Suppose we need to include double quotes inside a string. // include double quote string str = "This is the "String" class"; Since strings are represented by double quotes, the compiler will treat "This is the " as the string. And the above code will cause an error. To solve this issue, we use the escape character " in C#. For example, // use the escape character string str = "This is the "String" class."; Now by using before double quote ", we can include it in the string. Some of the escape sequences in C# are as follows: Escape Sequence Character Name ' single quote " double quote backslash 0 null n new line t horizontal tab String interpolation ➢ In C#, we can use string interpolation to insert variables inside a string. ➢ For string interpolation, the string literal must begin with the $ character. For example, using System; namespace CsharpString {
  • 41. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 41 class Test { public static void Main(string [] args) { // create string string name = "Programiz"; // string interpolation string message = $"Welcome to {name}"; Console.WriteLine(message); Console.ReadLine(); } } } Output: Welcome to Programiz In the above example, we are using the name variable inside the message string. string message = $"Welcome to {name}"; Notice that, ▪ the string literal starts with $ ▪ the name variable is placed inside the curly braces {} Methods of C# string There are various string methods in C#. Some of them are as follows: Methods Description Format() returns a formatted string Split() splits the string into substring Substring() returns substring of a string Compare() compares string objects Replace() replaces the specified old character with the specified new character Contains() checks whether the string contains a substring Join() joins the given strings using the specified separator Trim() removes any leading and trailing whitespaces EndsWith() checks if the string ends with the given string IndexOf() returns the position of the specified character in the string Remove() returns characters from a string ToUpper() converts the string to uppercase ToLower() converts the string to lowercase PadLeft() returns string padded with spaces or with a specified Unicode character on the left PadRight() returns string padded with spaces or with a specified Unicode character on the right StartsWith() checks if the string begins with the given string ToCharArray() converts the string to a char array
  • 42. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 42 LastIndexOf() returns index of the last occurrence of a specified string Structures ➢ In C#, a structure is a value type data type. ➢ It helps you to make a single variable hold related data of various data types. ➢ The struct keyword is used for creating a structure. ➢ Structures are used to represent a record. Suppose you want to keep track of your books in a library. ➢ You might want to track the following attributes about each book − ▪ Title ▪ Author ▪ Subject ▪ Book ID Defining a Structure ➢ To define a structure, you must use the struct statement. ➢ The struct statement defines a new data type, with more than one member for your program. For example, here is the way you can declare the Book structure − struct Books { public string title; public string author; public string subject; public int book_id; }; The following program shows the use of the structure − using System; struct Books { public string title; public string author; public string subject; public int book_id; }; public class testStructure { public static void Main(string[] args) { Books Book1; /* Declare Book1 of type Book */ Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = "C# Programming"; Book1.author = "vinutha"; Book1.subject = "C# Programming Tutorial"; Book1.book_id = 6495407; /* book 2 specification */ Book2.title = "Telecom Billing"; Book2.author = "Raju"; Book2.subject = "Telecom Billing Tutorial"; Book2.book_id = 6495700; /* print Book1 info */
  • 43. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 43 Console.WriteLine( "Book 1 title : {0}", Book1.title); Console.WriteLine("Book 1 author : {0}", Book1.author); Console.WriteLine("Book 1 subject : {0}", Book1.subject); Console.WriteLine("Book 1 book_id :{0}", Book1.book_id); /* print Book2 info */ Console.WriteLine("Book 2 title : {0}", Book2.title); Console.WriteLine("Book 2 author : {0}", Book2.author); Console.WriteLine("Book 2 subject : {0}", Book2.subject); Console.WriteLine("Book 2 book_id : {0}", Book2.book_id); Console.ReadKey(); } } When the above code is compiled and executed, it produces the following result – Book 1 title : C# Programming Book 1 author : vinutha Book 1 subject : C# Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Raju Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700 Features of C# Structures You have already used a simple structure named Books. Structures in C# are quite different from that in traditional C or C++. The C# structures have the following features − ➢ Structures can have methods, fields, indexers, properties, operator methods, and events. ➢ Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed. ➢ Unlike classes, structures cannot inherit other structures or classes. ➢ Structures cannot be used as a base for other structures or classes. ➢ A structure can implement one or more interfaces. ➢ Structure members cannot be specified as abstract, virtual, or protected. ➢ When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator. ➢ If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized. ➢ Class versus Structure ➢ Classes and Structures have the following basic differences − ➢ classes are reference types and structs are value types ➢ structures do not support inheritance ➢ structures cannot have default constructor In the light of the above discussions, let us rewrite the previous example − using System; struct Books { private string title; private string author;
  • 44. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 44 private string subject; private int book_id; public void getValues(string t, string a, string s, int id) { title = t; author = a; subject = s; book_id = id; } public void display() { Console.WriteLine("Title : {0}", title); Console.WriteLine("Author : {0}", author); Console.WriteLine("Subject : {0}", subject); Console.WriteLine("Book_id :{0}", book_id); } }; public class testStructure { public static void Main(string[] args) { Books Book1 = new Books(); /* Declare Book1 of type Book */ Books Book2 = new Books(); /* Declare Book2 of type Book */ /* book 1 specification */ Book1.getValues("C# Programming", "vinutha", "C Programming Tutorial",6495407); /* book 2 specification */ Book2.getValues("Telecom Billing", "Raju", "Telecom Billing Tutorial", 6495700); /* print Book1 info */ Book1.display(); /* print Book2 info */ Book2.display(); Console.ReadKey(); } } When the above code is compiled and executed, it produces the following result – Title : C# Programming Author : vinutha Subject : C# Programming Tutorial Book_id : 6495407
  • 45. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 45 Title : Telecom Billing Author : Raju Subject : Telecom Billing Tutorial Book_id : 6495700 Enums ➢ An enumeration is a set of named integer constants. ➢ An enumerated type is declared using the enum keyword. ➢ C# enumerations are value data type. ➢ In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance. Declaring enum Variable The general syntax for declaring an enumeration is − enum <enum_name> { enumeration list }; Where, • The enum_name specifies the enumeration type name. • The enumeration list is a comma-separated list of identifiers. Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example − enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat }; Example: The following example demonstrates use of enum variable − using System; namespace EnumApplication { class EnumProgram { enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat }; static void Main(string[] args) { int WeekdayStart = (int)Days.Mon; int WeekdayEnd = (int)Days.Fri; Console.WriteLine("Monday: {0}", WeekdayStart); Console.WriteLine("Friday: {0}", WeekdayEnd); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result – Monday: 1 Friday: 5
  • 46. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 46 OOPS With C# Class and Object • Class and Object are the basic concepts of Object-Oriented Programming which revolve around the real- life entities. • A class is a user-defined blueprint or prototype from which objects are created. • Basically, a class combines the fields and methods (member function which defines actions) into a single unit. • In C#, classes support polymorphism, inheritance and also provide the concept of derived classes and base classes. Declaration of class • Generally, a class declaration contains only a keyword class, followed by an identifier(name) of the class. • But there are some optional attributes that can be used with class declaration according to the application requirement. • In general, class declarations can include these components, in order: Modifiers: A class can be public or internal etc. By default modifier of the class is internal. Keyword class: A class keyword is used to declare the type class. Class Identifier: The variable of type class is provided. The identifier (or name of the class) should begin with an initial letter which should be capitalized by convention. Base class or Super class: The name of the class’s parent (superclass), if any, preceded by the : (colon). This is optional. Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded by the : (colon). A class can implement more than one interface. This is optional. Body: The class body is surrounded by { } (curly braces). Constructors in class are used for initializing new objects. Fields are variables that provide the state of the class and its objects, and methods are used to implement the behavior of the class and its objects. Example: // declaring public class public class sample { // field variable public int a, b;
  • 47. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 47 // member function or method public void display() { Console.WriteLine(“Class & Objects in C#”); } } Objects It is a basic unit of Object-Oriented Programming and represents real-life entities. A typical C# program creates many objects, which as you know, interact by invoking methods. An object consists of: State: It is represented by attributes of an object. It also reflects the properties of an object. Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects. Identity: It gives a unique name to an object and enables one object to interact with other objects. Consider Dog as an object and see the below diagram for its identity, state, and behavior. Objects correspond to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”. Declaring Objects (Also called instantiating a class) When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.
  • 48. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 48 Example: As we declare variables like (type name;). This notifies the compiler that we will use the name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. So for reference variable, the type must be strictly a concrete class name. Dog tuffy; If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object. Initializing an object The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor. Example: C# // C# program to illustrate the // Initialization of an object using System; // Class Declaration public class Dog { // Instance Variables String name; String breed; int age; String color; // Constructor Declaration of Class public Dog(String name, String breed, int age, String color) { this.name = name; this.breed = breed; this.age = age; this.color = color;
  • 49. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 49 } // Property 1 public String GetName() { return name; } // Property 2 public String GetBreed() { return breed; } // Property 3 public int GetAge() { return age; } // Property 4 public String GetColor() { return color; } // Method 1 public String ToString() { return ("Hi my name is " + this.GetName() + ".nMy breed, age and color are " + this.GetBreed() + ", " + this.GetAge() + ", " + this.GetColor()); }
  • 50. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 50 // Main Method public static void Main(String[] args) { // Creating object Dog tuffy = new Dog("tuffy", "papillon", 5, "white"); Console.WriteLine(tuffy.ToString()); } } Output: Hi my name is tuffy. My breed, age and color are papillon, 5, white Inheritance • In C#, inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which is defined in other class. • In C#, the class which inherits the members of another class is called derived class and the class whose members are inherited is called base class. The derived class is the specialized class for the base class. Advantage of C# Inheritance • Code reusability: Now you can reuse the members of your parent class. So, there is no need to define the member again. So less code is required in the class. • C# Single Level Inheritance Example: Inheriting Fields • When one class inherits another class, it is known as single level inheritance. Let's see the example of single level inheritance which inherits the fields only. using System; public class Employee { public float salary = 40000; } public class Programmer: Employee { public float bonus = 10000;
  • 51. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 51 } class TestInheritance{ public static void Main(string[] args) { Programmer p1 = new Programmer(); Console.WriteLine("Salary: " + p1.salary); Console.WriteLine("Bonus: " + p1.bonus); } } Output: Salary: 40000 Bonus: 10000 In the above example, Employee is the base class and Programmer is the derived class. C# Single Level Inheritance Example: Inheriting Methods Let's see another example of inheritance in C# which inherits methods only. using System; public class Animal { public void eat() { Console.WriteLine("Eating..."); } } public class Dog: Animal { public void bark() { Console.WriteLine("Barking..."); } } class TestInheritance2{ public static void Main(string[] args) { Dog d1 = new Dog(); d1.eat(); d1.bark(); } }
  • 52. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 52 Output: Eating... Barking... C# Multi Level Inheritance Example When one class inherits another class which is further inherited by another class, it is known as multi level inheritance in C#. Inheritance is transitive so the last derived class acquires all the members of all its base classes. Let's see the example of multi level inheritance in C#. using System; public class Animal { public void eat() { Console.WriteLine("Eating..."); } } public class Dog: Animal { public void bark() { Console.WriteLine("Barking..."); } } public class BabyDog : Dog { public void weep() { Console.WriteLine("Weeping..."); } } class TestInheritance2{ public static void Main(string[] args) { BabyDog d1 = new BabyDog(); d1.eat(); d1.bark(); d1.weep(); } } Output: Eating... Barking... Weeping... Note: Multiple inheritance is not supported in C# through class.
  • 53. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 53 C# Aggregation (HAS-A Relationship) In C#, aggregation is a process in which one class defines another class as any entity reference. It is another way to reuse the class. It is a form of association that represents HAS-A relationship. C# Aggregation Example Let's see an example of aggregation where Employee class has the reference of Address class as data member. In such way, it can reuse the members of Address class. using System; public class Address { public string addressLine, city, state; public Address(string addressLine, string city, string state) { this.addressLine = addressLine; this.city = city; this.state = state; } } public class Employee { public int id; public string name; public Address address;//Employee HAS-A Address public Employee(int id, string name, Address address) { this.id = id; this.name = name; this.address = address; } public void display() { Console.WriteLine(id + " " + name + " " + address.addressLine + " " + address.city + " " + address.state); } } public class TestAggregation
  • 54. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 54 { public static void Main(string[] args) { Address a1=new Address("G-13, Sec-3","Noida","UP"); Employee e1 = new Employee(1,"Sonoo",a1); e1.display(); } } Output: 1 Sonoo G-13 Sec-3 Noida UP Inheritance and an "is a" relationship Ordinarily, inheritance is used to express an "is a" relationship between a base class and one or more derived classes, where the derived classes are specialized versions of the base class; the derived class is a type of the base class. For example, the Publication class represents a publication of any kind, and the Book and Magazine classes represent specific types of publications. Note A class or struct can implement one or more interfaces. While interface implementation is often presented as a workaround for single inheritance or as a way of using inheritance with structs, it is intended to express a different relationship (a "can do" relationship) between an interface and its implementing type than inheritance. An interface defines a subset of functionality (such as the ability to test for equality, to compare or sort objects, or to support culture-sensitive parsing and formatting) that the interface makes available to its implementing types. C# Polymorphism Polymorphism and Overriding Methods Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. Like we specified in the previous chapter; Inheritance lets us inherit fields and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways. C# Member Overloading If we create two or more members having same name but different in number or type of parameter, it is known as member overloading. In C#, we can overload:
  • 55. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 55 methods, constructors, and indexed properties It is because these members have parameters only. C# Method Overloading Having two or more methods with same name but different in parameters, is known as method overloading in C#. The advantage of method overloading is that it increases the readability of the program because you don't need to use different names for same action. using System; public class Cal{ public static int add(int a,int b){ return a + b; } public static int add(int a, int b, int c) { return a + b + c; } } public class TestMemberOverloading { public static void Main() { Console.WriteLine(Cal.add(12, 23)); Console.WriteLine(Cal.add(12, 23, 25)); } } Output: 35 60
  • 56. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 56 C# Method Overriding If derived class defines same method as defined in its base class, it is known as method overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of the method which is already provided by its base class. To perform method overriding in C#, you need to use virtual keyword with base class method and override keyword with derived class method. C# Method Overriding Example Let's see a simple example of method overriding in C#. In this example, we are overriding the eat() method by the help of override keyword. class Parent { public virtual void Demo() // base class { Console.WriteLine(“This is parent”); } } class Child: Parent { public override void Demo() // derived class { Console.WriteLine(“This is child”); } } public static void main() { Child c=new child(); c.Demo(); } Interfaces Another way to achieve abstraction in C#, is with interfaces. An interface is a completely "abstract class", which can only contain abstract methods and properties (with empty bodies):
  • 57. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 57 Example // interface interface Animal { void animalSound(); // interface method (does not have a body) void run(); // interface method (does not have a body) } It is considered good practice to start with the letter "I" at the beginning of an interface, as it makes it easier for yourself and others to remember that it is an interface and not a class. By default, members of an interface are abstract and public. Note: Interfaces can contain properties and methods, but not fields. To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class. To implement an interface, use the : symbol (just like with inheritance). The body of the interface method is provided by the "implement" class. Note that you do not have to use the override keyword when implementing an interface: Example // Interface interface IAnimal { void animalSound(); // interface method (does not have a body) } // Pig "implements" the IAnimal interface class Pig : IAnimal { public void animalSound() { // The body of animalSound() is provided here Console.WriteLine("The pig says: wee wee"); } } class Program {
  • 58. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 58 static void Main(string[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); } } Notes on Interfaces: Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an "IAnimal" object in the Program class) • Interface methods do not have a body - the body is provided by the "implement" class • On implementation of an interface, you must override all of its methods • Interfaces can contain properties and methods, but not fields/variables • Interface members are by default abstract and public • An interface cannot contain a constructor (as it cannot be used to create objects) Why And When to Use Interfaces? 1) To achieve security - hide certain details and only show the important details of an object (interface). 2) C# does not support "multiple inheritance" (a class can only inherit from one base class). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below). interface IFirstInterface { void myMethod(); // interface method } interface ISecondInterface { void myOtherMethod(); // interface method } // Implement multiple interfaces class DemoClass : IFirstInterface, ISecondInterface {
  • 59. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 59 public void myMethod() { Console.WriteLine("Some text.."); } public void myOtherMethod() { Console.WriteLine("Some other text..."); } } class Program { static void Main(string[] args) { DemoClass myObj = new DemoClass(); myObj.myMethod(); myObj.myOtherMethod(); } } C# - 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. 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. Syntax
  • 60. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 60 Assuming a block raises an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following − 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 } You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations. Exception Classes in C# C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes. The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class. The System.SystemException class is the base class for all predefined system exception. The following table provides some of the predefined exception classes derived from the Sytem.SystemException class − Sr.No. Exception Class & Description 1 System.IO.IOException Handles I/O errors. 2 System.IndexOutOfRangeException Handles errors generated when a method refers to an array index out of range. 3 System.ArrayTypeMismatchException Handles errors generated when type is mismatched with the array type.
  • 61. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 61 4 System.NullReferenceException Handles errors generated from referencing a null object. 5 System.DivideByZeroException Handles errors generated from dividing a dividend with zero. 6 System.InvalidCastException Handles errors generated during typecasting. 7 System.OutOfMemoryException Handles errors generated from insufficient free memory. 8 System.StackOverflowException Handles errors generated from stack overflow. Handling Exceptions C# provides a structured solution to the exception handling in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements. These error handling blocks are implemented using the try, catch, and finally keywords. Following is an example of throwing an exception when dividing by zero condition occurs − using System; namespace ErrorHandlingApplication { class DivNumbers { int result; DivNumbers() { result = 0; } public void division(int num1, int num2) { try { result = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine("Exception caught: {0}", e); } finally { Console.WriteLine("Result: {0}", result);
  • 62. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 62 } } static void Main(string[] args) { DivNumbers d = new DivNumbers(); d.division(25, 0); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Exception caught: System.DivideByZeroException: Attempted to divide by zero. at ... Result: 0 Creating User-Defined Exceptions You can also define your own exception. User-defined exception classes are derived from the Exception class. The following example demonstrates this − using System; namespace UserDefinedException { class TestTemperature { static void Main(string[] args) { Temperature temp = new Temperature(); try { temp.showTemp(); } catch(TempIsZeroException e) { Console.WriteLine("TempIsZeroException: {0}", e.Message); } Console.ReadKey(); } } } public class TempIsZeroException: Exception { public TempIsZeroException(string message): base(message) { }
  • 63. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 63 } public class Temperature { int temperature = 0; public void showTemp() { if(temperature == 0) { throw (new TempIsZeroException("Zero Temperature found")); } else { Console.WriteLine("Temperature: {0}", temperature); } } } When the above code is compiled and executed, it produces the following result − TempIsZeroException: Zero Temperature found Throwing Objects You can throw an object if it is either directly or indirectly derived from the System.Exception class. You can use a throw statement in the catch block to throw the present object as − Catch(Exception e) { ... Throw e } 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. Declaring Delegates Delegate declaration determines the methods that can be referenced by the delegate. A delegate can refer to a method, which has the same signature as that of the delegate. For example, consider a delegate − public delegate int MyDelegate (string s); The preceding delegate can be used to reference any method that has a single string parameter and returns an int type variable.
  • 64. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 64 Syntax for delegate declaration is – delegate <return type> <delegate-name> <parameter list> Instantiating Delegates Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a particular method. When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method. For example : public delegate void printString(string s); ... printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile); Following example demonstrates declaration, instantiation, and use of a delegate that can be used to reference methods that take an integer parameter and returns an integer value. using System; delegate int NumberChanger(int n); namespace DelegateAppl { class TestDelegate { static int num = 10; public static int AddNum(int p) { num += p; return num; } public static int MultNum(int q) { num *= q; return num; } public static int getNum() { return num; }
  • 65. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 65 static void Main(string[] args) { //create delegate instances NumberChanger nc1 = new NumberChanger(AddNum); NumberChanger nc2 = new NumberChanger(MultNum); //calling the methods using the delegate objects nc1(25); Console.WriteLine("Value of Num: {0}", getNum()); nc2(5); Console.WriteLine("Value of Num: {0}", getNum()); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Value of Num: 35 Value of Num: 175 Multicasting of a Delegate Delegate objects can be composed using the "+" operator. A composed delegate calls the two delegates it was composed from. Only delegates of the same type can be composed. 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. This is called multicasting of a delegate. The following program demonstrates multicasting of a delegate − using System; delegate int NumberChanger(int n); namespace DelegateAppl { class TestDelegate { static int num = 10; public static int AddNum(int p) { num += p;
  • 66. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 66 return num; } public static int MultNum(int q) { num *= q; return num; } public static int getNum() { return num; } static void Main(string[] args) { //create delegate instances NumberChanger nc; NumberChanger nc1 = new NumberChanger(AddNum); NumberChanger nc2 = new NumberChanger(MultNum); nc = nc1; nc += nc2; //calling multicast nc(5); Console.WriteLine("Value of Num: {0}", getNum()); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Value of Num: 75 Using Delegates The following example demonstrates the use of delegate. The delegate printString can be used to reference method that takes a string as input and returns nothing. We use this delegate to call two methods, the first prints the string to the console, and the second one prints it to a file − using System;
  • 67. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 67 using System.IO; namespace DelegateAppl { class PrintString { static FileStream fs; static StreamWriter sw; // delegate declaration public delegate void printString(string s); // this method prints to the console public static void WriteToScreen(string str) { Console.WriteLine("The String is: {0}", str); } //this method prints to a file public static void WriteToFile(string s) { fs = new FileStream("c:message.txt", FileMode.Append, FileAccess.Write); sw = new StreamWriter(fs); sw.WriteLine(s); sw.Flush(); sw.Close(); fs.Close(); } // this method takes the delegate as parameter and uses it to // call the methods as required public static void sendString(printString ps) { ps("Hello World"); } static void Main(string[] args) { printString ps1 = new printString(WriteToScreen);
  • 68. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 68 printString ps2 = new printString(WriteToFile); sendString(ps1); sendString(ps2); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − The String is: Hello World 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 − event BoilerLogHandler BoilerEventLog; The preceding code defines a delegate named BoilerLogHandler and an event named BoilerEventLog, which invokes the delegate when it is raised. Example using System; namespace SampleApp { public delegate string MyDel(string str);
  • 69. C#.NET SHREE MEDHA DEGREE COLLEGE, BALLARI Dept of Computer Science From the desk of Ms. Vinutha H M M.Sc. (CS) Page 69 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("Tutorials Point"); Console.WriteLine(result); } } } When the above code is compiled and executed, it produces the following result − Welcome Tutorials Point