Você está na página 1de 76

www.dbakings.

com
Contents: Chapter 1 Introduction to C#.NET Rules in C#.NET Datatypes Operators Creating first console application Basic C#.NET program structure in Console Application Console Methods Write WriteLine Read ReadLine Chapter 2 Variables Predefined Methods Implicit Conversion Explicit Conversion Boxing UnBoxing Chapter 3 Arrays Single dimension arrays Multidimensional arrays Jagged Array Chapter 4 Conditional statements Branching Looping If If Else

Copyrights Chekuri group

www.dbakings.com
Else if Nested if Switch Chapter 5 for for each while do while Chapter 6 OOPS methods General methods Methods with arguments Methods with return type Methods with arguments and return type Static method Class Object Chapter 7 Encapsulation Inheritance Single inheritance Multi level inheritance Hierachical inheritance Multiple inheritance Hybrid inheritance Sealed class Chapter 8 Abstraction Access specifiers

Copyrights Chekuri group

www.dbakings.com
Private Public Protected Internal Protected Internal Creating userdefined namespace or dll Chapter 9 Polymorphism Method overloading Method overriding Abstract method Abstract class Partial class Chapter 10 Interface Inheriting Multiple interfaces Delegates Single delegates Multcast delegates Exception handling Try Catch Finally Throw

Copyrights Chekuri group

www.dbakings.com

Chapter 1 Introduction to C#.NET C#.NET is an object oriented programming language and it is a part of .NET. It is used as a code behind language in DOTNET applications. It is the most popular language in .NET because it has the same syntax of programming languages like C, C++, JAVA. It is written as C# but pronounced as C Sharp because # is not taken from maths it is a musical note which is pronounced as Sharp. It is a case sensitive language i.e., Lowercase letter is not same as Uppercase letter. Example int i; and int I; they are different variables. Every block of code starts with opening curly brace and end with closing curly brace. opening brace { } closing brace All the keywords in C# will be in lowercase. Example int, using, class, ... Predefined namespaces, classes and methods will start with uppercase letter(Every word starts with uppercase letter). Example System, Console, Read Namespace is a collection of classes. Class is a collection of methods and its members. Rules in C#.NET

Copyrights Chekuri group

www.dbakings.com
Every C# statement should end with semicolon (;). Example Console.Write("hello world"); Every string value should be surrounded by double quotes. Example string s="hai"; Every character value should be surrounded by single quotes. Example char c='a'; No need of any quotes around numeric values. Example int i=515; float f=533.558f; Every line of code in C# should be in class. // is for comments in C#

Datatypes Datatypes and memory in bytes Byte Short Int Long Sbyte Ushort Uint Ulong Float Double Decimal Bool Char String Object 1 2 4 8 1 2 4 4 4 8 16 1 2 20+ 8+

Copyrights Chekuri group

www.dbakings.com

Example program with all datatypes using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace datatypes { class Program {//main function is the starting point static void Main(string[] args) { int i = 10; int j = 20; //int i = 234.234; //the text in double quotes will print as it is and value in i variable is printed next to that. Console.WriteLine("int: "+i); //int: 10 Console.WriteLine("sum: "+(i+j)); //sum: 30

float f = 23.23f; float f1 = 245; Console.WriteLine("float: "+(f+f1));//float: 268.23

char c = 'a'; // char c='abad'; // char c = a; Console.WriteLine("char: "+c);//char: a

string s = "abc"; // string s = abc;

Copyrights Chekuri group

www.dbakings.com
//string s='abd'; string s1 = "def"; Console.WriteLine(s+s1);//abcdef Console.WriteLine("string: "+s+s1);//string: abcdef //+ is used as concatenation(side by side) for strings //+ is used as addition operator for numeric datatypes Console.WriteLine(s+"\n"+s1); // \n is used to go to new line it should be in double quotes bool b = true; bool b1 = false; //bool b2 = "abc"; Console.WriteLine(b);//true Console.WriteLine(b1);//false

object o = 123; object o1 = 'a'; object o2 = "abc"; object o3 = 234.234f; object o4 = true;

Console.WriteLine("object: "+o3);

Console.ReadKey(); } } }

Copyrights Chekuri group

www.dbakings.com

Operators Arithmetic operators: Used to work with numeric data types. eg: int , float, double, long, decimal, short... + (addition) eg: a+b - (substraction) eg: a-b * (multiplication) eg: a* b / (division) eg: a/b % (modulus) eg: a%b = equal to Assignment operators; += eg: a+=b; ie., a=a+b; -= eg: a-=b; ie., a=a-b; *= eg: a*=b; ie., a=a*b; /= eg: a/=b; ie., a=a/b; %= eg: a%=b; ie., a=a%b;

Copyrights Chekuri group

www.dbakings.com
Unary operator; ++ (increment) -- (decrement) i++(post increment) 1 is added to i after the code is executed. ++i (pre increment) 1 is added to i before the code gets executed. i--(post decrement) i is decreased by 1 after the code is executed. --i(pre decrement) i is decreased by 1 before the code gets executed. Example program using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int i = 1; int j = i++; Console.WriteLine(j);//1 Console.WriteLine(i);//2 Console.WriteLine("----------------------"); int x = 1; int y = ++x; Console.WriteLine(y);//2

Copyrights Chekuri group

www.dbakings.com
Console.WriteLine(x);//2 Console.ReadKey(); } } } Relational operators: Used to compare two values in variables. Used in conditional statements. > greater than < less than >= greater than or equal to <= less than or equal to == equals to != not equal to Logical operators: && (logical and) when both are satisfied. || (logical or) when one of them is satisfied Bit wise operators: & (bitwise and) | (bitwise or) ^ (bitwise xor) ! (bitwise not) Shift operators: << (shift left) (*) eg: a=3<<4 ie., 3*2^4 =48 >> (shift right) (/)

Copyrights Chekuri group

www.dbakings.com
eg: a=3>>4 ie., 3/2^4 =146

Operator precedence: Based on the operator priority arthmetic statements are solved. bodmas brackets, division, multiplication, addition, substraction. Creating first console application Open visual studio. Click on file in menu. New project. Select a language as c# from the left side. Select console application from the list of applications. Give the name to the project Select the location to save the project. click on ok. Now default environment to create console application is displayed. F5 is the shortcut key to start debugging or to execute a program (or) click on play symbol button present in the center of top menu of visual studio tool. Shift + F5 for stop debugging or execution.

Basic C#.NET program structure in Console Application using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace first { class Program {

Copyrights Chekuri group

www.dbakings.com
static void Main(string[] args) { } } } Explanation: using - using is a keyword used to import a namespace to use the classes inside it in your coding. System - System is a namespace name which consists of classes used in coding. Like System we also have many namespaces given by Microsoft. By default we get the above four namespaces. first - first is the project name what you have given while creating this console application. Program - Program is the default class name for every console application. Main - Main is the method is acts as the starting point for every application. There should be only one main function for every project. Main is a static method which is created using static keyword and as it is a static method memory for main is created in ram when program is executed. void - void is the return type of Main method. Method with void return type returns nothing so main method also returns nothing. string[] args - Main method will take input arguments in the form of string array. We can also remove the namespaces like System.Text which are not used in the program. Console Methods Console is a class under System namespace. Under Console class we have 5 important methods. 1. ReadKey 2. Write

Copyrights Chekuri group

www.dbakings.com
3. WriteLine 4. Read 5. ReadLine These five methods plays a prominent role in developing console applications. If System namespace is not added at the top of the program we have to use it everywhere where Console class is used. Example: Console.Write("System is added"); System.Console.Write("System is not added"); ReadKey

ReadKey method is under Console class used to stop the output screen of a console application from closing immediately after program execution till we press a key. So use Console.ReadKey( ) line at the end of Main function in every program to see the output. It doesn't take any parameter between the braces.

Example program to print a simple message using ReadKey: using System; namespace readkey { class Program { static void Main(string[] args) { Console.ReadKey(); } } }

Copyrights Chekuri group

www.dbakings.com
Output: _ Explanation: Blank blank ouput screen waits without closing till you press a key this is because of ReadKey method. If that line is removed the output screen will close immediately after program execution completed. Write

Write method is under Console class. It is used to print a message on the output screen of console application. When you print a message using Write the cursor will appear next to the message. It prints the text as it is present in the double quotes. It also prints the value present in variable.

Example program to print a simple message using Write: using System; namespace write { class Program { static void Main(string[] args) { Console.Write("Hai this is Write example"); Console.ReadKey(); } } }

Copyrights Chekuri group

www.dbakings.com
Output: Hai this is Write example_ Explanation: In the above program Write is a method under Console class used to print a message on the output screen with a cursor blinking next to message. As Console class is under System namespace we have to add it at the top. ReadKey method is used to make output screen without closing immediately. We can also write the above program without adding System namespace as below. Example program to print a simple message on using Write without adding System namespace: namespace write { class Program { static void Main(string[] args) { System.Console.Write("Hai this is Write example"); System.Console.ReadKey(); } } }

Output: Hai this is Write example_ Explanation:

Copyrights Chekuri group

www.dbakings.com
As Console class is under System namespace we have to add it at the top otherwise we have to add it before Console class everywhere in the program where we use Console class.

WriteLine WriteLine method is under Console class used to print message on the output screen of console application. When you print a message using WriteLine the cursor will appear in the next line of the message.

Example program to print a simple message using WriteLine: using System; namespace writeline { class Program { static void Main(string[] args) { Console.WriteLine("Hai this is Write example"); Console.ReadKey(); } } } Output: Hai this is Write example _ Explanation: In the above program WriteLine is a method under Console class used to print a message on the output screen with a cursor blinking in the next line of message.

Copyrights Chekuri group

www.dbakings.com

Read

Read method is under Console class used to Read data from the user given in runtime. When you read a message using Read the cursor will appear in the same line. Return type of Read method is int ie., it returns back the data given by the user in the form of int. It returns ascii value of the given data. It doesn't take any parameter between the braces.

Example: int i=Console.Read(); Console.Write(i); if the user enters a its ascii value 97 is stored in i. Here, Console.Write method is used to print the value inside i, So, the output will be 97. Example program to print a simple message using Read: using System; namespace read { class Program { static void Main(string[] args) { int i=Console.Read(); Console.Write("\n"); Console.Write("you entered: "+i); Console.ReadKey(); } }

Copyrights Chekuri group

www.dbakings.com
} Output: a you entered: 97_ Explanation: In the above program i is a variable of int datatype which is used to store the ascii value of the data given by user in runtime using Read method. First Write method is used for new line and second Write method is used to print message "you entered: " as it is and also to concatenate the value present in the variable i as show in the output. ReadLine

ReadLine method is under Console class used to Read data from the user given in runtime. When you read a message using ReadLine the cursor will appear in the next line. Return type of ReadLine method is string ie., it returns back the data given by the user in the form of string. It returns the value as it is given by the user so ReadLine method is preferred to take input data from the user in runtime. It doesn't take any parameter between the braces.

Example: string s=Console.ReadLine(); Console.Write(s); if the user enters a then a as it is stored in string variable s. Here, Console.Write method is used to print the value inside s, So, the output will be a.

Copyrights Chekuri group

www.dbakings.com
Example program to print a simple message using ReadLine: using System; namespace readline { class Program { static void Main(string[] args) { string s=Console.ReadLine(); Console.Write("you entered: "+s); Console.ReadKey(); } } } Output: a you entered: a_ Explanation: In the above program s is a variable of string datatype which is used to store the value given by user in runtime using ReadLine method. Write method is used to print message "you entered: " as it is and also to concatenate the value present in the variable s as show in the output.

Chapter 2 Variables Variable is used to store a value of a specific datatype. Memory for a variable is allocated in stack memory. The value is a variables keeps on changing throughout the program.

Copyrights Chekuri group

www.dbakings.com
Example: int i; i=10; Here i is a variable of type int. So, the value between -2,147,483,648 to 2,147,483,648 can be stored in variable i. In the second statement value 10 is stored in i. We can also intialize the variable with some value when it is created like below. Example program to create a variable of int type, initialization and also assigning value to it: using System; namespace variable { class Program { static void Main(string[] args) { int i=10; i = 20; Console.Write(i); Console.ReadKey(); } } } Output: 20_ Explanation: In the above program i is a variable of int datatype. It is intialized with a value of 10. In the next statement i is assigned with a new value 20. So, the value in the variable is changed from 10 to 20. When we print the value in variable i using WriteLine the output is 20.

Copyrights Chekuri group

www.dbakings.com
In the same way we can create any number of variables in a program with specific datatypes and based on the datatypes values should be stored in variables. Example program for creating variables with different datatypes and printing values in them: using System; namespace variable { class Program { static void Main(string[] args) { int i = 20; float f = 23.234f; char c = 'b'; string s = "def"; bool b = false; Console.WriteLine(i+f); Console.WriteLine(c+s); Console.WriteLine(i+c); Console.WriteLine(i+s); Console.WriteLine(b); Console.ReadKey(); } } } Output: 43.234 bdef 118 20def false _ Explanation: There are 4 variables i, f, c, s, b with datatypes int, float, char, string, bool respecitively.

Copyrights Chekuri group

www.dbakings.com
int and float is of numeric datatypes so variables i and f stores numbers and there is no need of having quotes around the values. f is of float type so it can store numeric value with decimal point but when f should be the suffix for the value which is assigned to f. c variable is of char type and it is capable of storing only one character at a time whereas variable s can store multiple characters as it is of string datatype. b variable is capable of storing either true or false value only. i + f = 20 + 23.234 = 43.234 As i and f are numeric types + is used as addition arthimetic operator and they are added. c + s= b + def = bdef As c is char and s is string + is used as concatenation operator and they are concatenated. i + c = 20 + b = 20 + 98 = 118 As i is integer and c is char the ascii value of c is added to i ie., ascii of b is 98 added to 20 gives output as 118. i + s = 20 + def = 20def As s is string it cannot be converted into ascii value so here + is used for concatenating values of i and s. b = false Value inside b is false and it is printed as it is. Predefined methods Predefined methods are the inbuilt methods we have in C#.NET which do something or returns a value. We have predefined methods like minvalue( ): min value is a method used to find out the minimum value a numeric datatype can store. It is only for numeric types. maxvalue( ): max value is a method used to find out the maximum value a numeric datatype can store.

Copyrights Chekuri group

www.dbakings.com
It is only for numeric types. Example program to print minvalue and maxvalue of numeric datatypes int, uint, long, float, double, decimal using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace min_max_value { class Program { static void Main(string[] args) { Console.WriteLine(int.MinValue); Console.WriteLine(int.MaxValue); Console.WriteLine(uint.MinValue); Console.WriteLine(uint.MaxValue); Console.WriteLine(long.MinValue); Console.WriteLine(long.MaxValue); Console.WriteLine(float.MinValue); Console.WriteLine(float.MaxValue); Console.WriteLine(double.MinValue); Console.WriteLine(double.MaxValue); Console.WriteLine(decimal.MinValue); Console.WriteLine(decimal.MaxValue); Console.ReadKey(); } } }

output:

Copyrights Chekuri group

www.dbakings.com
Example program to print even numbers between 10 and 45 using for loop and if condition:

using System; namespace variable { class Program { static void Main(string[] args) { for (int i = 10; i < 45; i++) { if (i % 2 == 0) { Console.WriteLine(i); } } Console.ReadKey(); } } } Output: 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38

Copyrights Chekuri group

www.dbakings.com
40 42 44

Implicit Conversion Converting small data type values to large data type values automatically by the compileris known as "Implicit Conversion". Example: int i=10; long l=i; Console.Write(l);//10 Explanation: int data type is smaller than long data type ie., int data type occupies small range as compare to long data type.so conversion of int to long is possible.it is an example of implicit conversion. Explicit conversion Converting large data type values to small data type values explicitly by the developer is known as "Explicit Conversion". Example: long l=10; int i=Convert.ToInt32(l); Console.Write(i);//10 Explanation: long data type is longer than int data type ie.,long occupies long range as compare to int.so conversion of long to int is difficult to the developer.so developer use the method Convert.ToInt32() to convert long values into int values.Then conversion is possible and easy. Boxing

Copyrights Chekuri group

www.dbakings.com
Converting value type to reference type is known as "Boxing". Example: int i=10; object o=i; Console.WriteLine(o);//10 Explanation: In the above example int datatype is value type.object is reference type.so conversion of int to object is possible and it is an example of boxing. UnBoxing Converting reference type to value type type is known as "UnBoxing". Example: object o=10; int i=Convert.ToInt32(o); Console.WriteLine(i);//10 Explanation: In the above example object is reference type.int is value type.conversion of object to int is not possible.so here we use Convert.ToInt32() to convert object to int.

Chapter 3 Arrays

Array is a type used to store multiple values of same data type under a single name. Arrays allows to store multiple values but all the values should be same data type. The elements can't exceed the number while creating an array. Arrays are zero indexed that means index starts with zero.

Copyrights Chekuri group

www.dbakings.com
Arrays are objects in c#.Memory objects are created in heap memory. Index of an array will be used to retrieve values. Array.Reverse()is used to reverse the elements of an array. Array.Sort() is used to print values in ascending order. Array.Length() is used to get the no.of elements in the array.

Single Dimensional Array Single Dimensional Array is used to store multiple values in a linear fashion. Syntax for creating a single dimensional array: datatype[ ] arrayname=new datatype[no. of elements]; Example: int[ ] i=new int[3]; Example program for creating single dimensional array using for loop: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace sdarray { class Program { static void Main(string[] args) { //int[] i = new int[3]; // i[0] = 1;------Assign a value // i[1] = 2;------Assign a value

Copyrights Chekuri group

www.dbakings.com
// i[2] = 3;------Assign a value int[] i = new int[3] { 1, 2, 3 }; for (int a = 0; a < 3; a++) { Console.WriteLine(i[a]); } Console.ReadKey(); } } } Output: 1 2 3

Example program for creating single dimensional array using foreach loop: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace sdarray { class Program { static void Main(string[] args) { int[] i = new int[3] { 3,4,5 }; foreach (int a in i) { Console.WriteLine(a); } Console.ReadKey();

Copyrights Chekuri group

www.dbakings.com
} } } Output: 3 4 5

Multi Dimensional Array Multi Dimensional Array is used to store elements in the form of a table. Syntax for creating a multi dimensional array: datatype[ , ] arrayname=new datatype[row,col]; Example: int[ ,] a=new int[2,3];

Example program for creating multi dimensional array using for loop: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace sdarray { class Program { static void Main(string[] args) { int[ , ] a = new int[2,3]{{5,6,3}, { 3,4,5} };

Copyrights Chekuri group

www.dbakings.com
for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { Console.Write(a[i, j]); } Console.WriteLine(""); } Console.ReadKey(); } } } Output: 563 345

Jagged Array Jagged array is a special type of array which is known as array in array. In this we have static rows and dynamic columns. Syntax for creating Jagged Array: datatype[ ][ ] arrayname=new datatype[rows][cols]; Example: int[ ][ ] a=new int[2][ ]; Example program for creating Jagged Array using for loop: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace sdarray

Copyrights Chekuri group

www.dbakings.com
{ class Program { static void Main(string[] args) { int[][] a = new int[2][]; a[0] = new int[3] { 3, 4, 5 }; a[1] = new int[4] { 1, 2, 3, 4 }; for (int i = 0; i < 2; i++) { for (int j = 0; j < a[i].Length; j++) { Console.Write(a[i][j]); } Console.WriteLine(""); } Console.ReadKey(); } } } Output: 345 1234

Chapter4 Conditional Statements A block of code that executes basing upon a condition is "Conditional Statement".Conditional statements are used to execute a block of code only when the condition is satisfied. Conditional statements are classified into two types. 1)Conditional Branching 2)Conditional Looping

Copyrights Chekuri group

www.dbakings.com

Conditional Branching These statements allows you to branch code depending on whether the certain conditions met or not. C# has two constructs for branching code. 1)If Statement 2)Switch Statement

Conditional Looping C# provides four different loops that allows you to execute a block of code repeatedly until a certain condition is met. Those are: 1) for loop 2) while loop 3) dowhile loop 4) foreach loop

If Statement: The if statement which allows you to test whether a specific condition is met. Syntax of If Condition: if(condition) { //statements } Example program using if condition using System; using System.Collections.Generic; using System.Linq;

Copyrights Chekuri group

www.dbakings.com
using System.Text; namespace branching { class Program { static void Main(string[] args) { int i; Console.WriteLine("Enter number"); i = Convert.ToInt32(Console.ReadLine()); if (i > 0) { Console.WriteLine("Positive"); } Console.ReadKey(); } } } Output: Enter number 12 Positive Output-2: Enter number -5 _ Explanation: In the above output we can give input is -5.here -5 is less than zero.so nothing will be printed in output. Blank will be printed in output.

If else statement:

Copyrights Chekuri group

www.dbakings.com
It is one of the statement in conditional branching. It is used to check whether the condition is true or false. if it is true, it goes to if condition and print output. if it is false, it goes to else part of the program and print the output. Syntax for if else statement: if(condition) { statement } else { statement } Example program using if else statement using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ifelse { class Program { static void Main(string[] args) { int i; Console.WriteLine("Enter number"); i = Convert.ToInt32(Console.ReadLine()); if (i > 0) { Console.WriteLine("Positive"); } else { Console.WriteLine("Negative");

Copyrights Chekuri group

www.dbakings.com
} Console.ReadKey(); } } } Output: Enter number 12 Positive Output-1: Enter number -6 Negative Explanation: In the above example we can give input is 12 then the output will be printed as positive because 12 is greaterthan zero.we can give input is -6 then the output will be printed as negative because -6 is less than zero.

Else if statement This is one type of conditional branching.In this type the compiler 1st goes to if condition,if it is false it goes to else if condition,it also false finally goes to else statement and print output. Syntax for Else if statement: if(condition) { statements } else if(condition) { statements

Copyrights Chekuri group

www.dbakings.com
} else { statements } Example program using Else if statement using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ifelse { class Program { static void Main(string[] args) { int i; Console.WriteLine("Enter number"); i = Convert.ToInt32(Console.ReadLine()); if (i > 0) { Console.WriteLine("Positive"); } else if(i<0) { Console.WriteLine("Negative"); } else { Console.WriteLine("zero"); } Console.ReadKey(); } } }

Copyrights Chekuri group

www.dbakings.com
Output: Enter number 223 Positive Output-1: Enter number -741 Negative Output-2: Enter number 0 zero Explanation: In the above example we give input is 223,it is greater than zero,then the output will be printed as positive and we give input is -741 it is less than zero,then the compiler goes to else if part of the program and print output as negative and finally gives 0 it is equal to zero,then the compiler goes to else pert of the program and print output as zero.

Nested If Statement It is one type of If statement.Nested If means if in if ie.,The if statement contains another if within that. Syntax for Nested If: if(condition) { if(condition) { if(condition) { statements

Copyrights Chekuri group

www.dbakings.com
} } } Example program for Nested If Statements using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ifelse { class Program { static void Main(string[] args) { int i; Console.WriteLine("Enter number"); i = Convert.ToInt32(Console.ReadLine()); if (i > 0) { if (i > 5 && i < 10) { Console.WriteLine("Between 5 and 10"); } } Console.ReadKey(); } } } Output: Enter number 4 _ Output-1: Enter number 8

Copyrights Chekuri group

www.dbakings.com
Between 5 and 10 Explanation: In the above example we can give input is 4,nothing will be printed in output because 4 is greater than zero but it is not in between 5 and 10.so,the output will be _.In second output we can give input is 8,it is in between 5 and 10 so,it will be printed as Between 5 and 10.

Switch Statement: The switch statement which allows you to compare an expression with a number of different values. Syntax of Switch statement: switch(variable) { case value1: statements; break; case value2: statements; break; ------------------------------------------------------default: statements; break; Example program using switch statement: using System; using System.Collections.Generic; using System.Linq; using System.Text;

Copyrights Chekuri group

www.dbakings.com
namespace branching { class Program { static void Main(string[] args) { Console.WriteLine("Enter number"); int no = Convert.ToInt32(Console.ReadLine()); switch (no) { case 1: Console.WriteLine("One"); break; case 2: Console.WriteLine("Two"); break; default: Console.WriteLine("Invalid"); break; } Console.ReadKey(); } } } Output: Enter number 1 One Output-1: Enter number 2 Two Output-2: Enter number

Copyrights Chekuri group

www.dbakings.com
12 Invalid Explanation: In the above example we can give input is 1 it prints output as One, input is 2 print output as Two, if we can give input is any number except 1 and 2 the output prints Invalid because if we can give input is 1 compiler executes case1 and we give i/p is 2 executes case2 then print output as One and Two.we give any other number except 1 and 2 default case will execute and prints Invalid. Another Example program for switch statement: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace branching { class Program { static void Main(string[] args) { int i = 4; switch (i) { case 1: case 2: case 3: Console.WriteLine("One"); break; case 4: case 5: Console.WriteLine("Two"); goto case 1; default: Console.WriteLine("Invalid");

Copyrights Chekuri group

www.dbakings.com
break; } Console.ReadKey(); } } } Output: Two One Explanation: In the above example we can assign i value as 4. So directly case 4 is executed and print output is Two, next no break statement is available. instead of break we write goto statement as goto case1,then after the execution go and starts from case1 then the output one will be printed. Finally the output will be Two and One printed line by line. Chapter5 1)for loop: for loop is used to execute a block of code repeatedly until the condition is true. for loops are appropriate when you know exactly how many times you want to perform the statements within the loop. Normally, for loop statements execute from the opening curly brace to the closing curly brace without interruption. Every for loop can contain three sections commonly. Those sections are: Initialization: Which sets the starting point of the loop. condition: The code is executed until the condition satisfied ie.,until it returns true value. Iteration(Increment/Decrement): Once Condition has been evaluated, the for loop gives to its control to third section ie., Iteration, which takes to the next side either positive or negative

Copyrights Chekuri group

www.dbakings.com
direction. Some times it will be incremented, sometimes decremented depending on the situation. Syntax for for loop: for(initialize; condition; inc/dec) { statements }

Example program using for loop using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace loops { class Program { static void Main(string[] args) { for (int i = 0; i < 4; i++) { for (int j = 0; j < i + 1; j++) { Console.Write("*"); } Console.WriteLine(""); } Console.ReadKey(); } } } Output: *

Copyrights Chekuri group

www.dbakings.com
** *** ****

2)foreach loop foreach loop is a special loop used for collections and arrays.It is repeated based on the number of elements in a collection.It automatically takes one by one element from a collection and it is repeated till the last element is printed. Syntax for foreach loop: foreach(type variable in collect:ion/array) { statements } Example program using foreach loop using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace loops { class Program { static void Main(string[] args) { int[] i = new int[3] { 7, 8, 9 }; foreach (int a in i) { Console.WriteLine(a); } Console.ReadKey();

Copyrights Chekuri group

www.dbakings.com
} } } Output: 7 8 9

3)While loop while loop will check a condition and then continues to execute a block of code as long as the condition is true. Syntax for While loop: while(condition) { statements } Example program to print numbers from 0 to 5 using while loop using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace loops { class Program { static void Main(string[] args) { int i=0; while (i <= 5) { Console.WriteLine(i);

Copyrights Chekuri group

www.dbakings.com
i++; } Console.ReadKey(); } } } Output: 0 1 2 3 4 5

4)Dowhile loop Dowhile loop is similar to the while loop, except that it checks its condition at the end of the loop. This means that the dowhile loop is guaranteed to execute at least one time even the condition fails. Syntax for dowhile loop: do { statements } while(condition); Example program to print numbers from 0 to 5 using dowhile loop using System; using System.Collections.Generic; using System.Linq; using System.Text;

Copyrights Chekuri group

www.dbakings.com
namespace loops { class Program { static void Main(string[] args) { int i=0; do { Console.WriteLine(i); i++; } while(i<=5); Console.ReadKey(); } } }

Output: 0 1 2 3 4 5

Difference between While and Dowhile loop: In while loop a block of code executed till the condition is satisfied. In Dowhile a block of code is executed atleast once and repeatedly executed till the condition is satisfied. In while condition checks first, then the code is executed. In Dowhile code is executed first and then the condition is checked.

Copyrights Chekuri group

www.dbakings.com
Chapter6 OOPS OOPS stands for Object Oriented Programming Structures. It was a new approach in programming introduced in 1970's Object Oriented approach provides us security and reusability of the code. To call a language as Object Oriented it needs to satisfy the below oops concepts listed below Encapsulation Abstraction Inheritance Polymorphism Before going to the discussion about oops concepts we have learn what a method, object and a class is. They are the basic building blocks in oops concepts. Methods Method is a named block of code or piece of code used to perform a particular task. Methods may or may not return a value. If it was a non value returning we use void as the return type for a method. If it was a value returning we use type of value as its return type.

Syntax for creating a method: Access_specifier return_type methodname( ) { //code } Access Specifier: It is used to define the accessibility level of a method ie.,how long it is going to call.

Copyrights Chekuri group

www.dbakings.com
ex of access specifiers are public, private, protected etc. ReturnType: What type of value a method is returning. Method name: The name of a method to call it. Example: public void add( ) {} There are different types of methods Simple Method Method with arguments Method with return type Method with arguments and return type Abstract Method Static Method

Simple Method Simple method is a method that doesn't have any arguments and return type. Syntax: Access specifier void methodname( ) {} Example: public void add() { Console.WriteLine("addition"); } The above method add will print addition as message on the ouput screen. This is a simple method which taken no input and doesnt return anything.

Copyrights Chekuri group

www.dbakings.com
Method with arguments It is one type of method and consists of arguments/parameters. Arguments can be passed to a method which are inputs to the method. The value passed to the method as arguments can be used in the code of the method. Example: public void add(int a,int b) { Console.WriteLine(a+b); } Explanation: In the above example the add( ) method can take two values of int type as inputs and doesn't return any type because void is its return type.

Method with Return Type It is one of the method that doesn't have any arguments/parameters. It contains only return type. Example: public int add() { int i=10; int j=20; return i+j; } Explanation: The above method add will return a value of int datatype.

Copyrights Chekuri group

www.dbakings.com

Method with arguments and return type It is one of the method that contains both arguments and return type. Example public long add(int a,int b) { return a+b; } Explanation: The above method add can take two parameters of int type and returns a value of long datatype. Abstract Method Abstract method is a method which is created using "abstract"keyword. It doesn't have any implementation or body. It will have only signature. semicolon is required at the end of signature. It is implemented in the class which inherits it. Syntax for creating abstract method: abstract keyword access_specifier return_type method_name(input parameters) Example: abstract public long add(int a,int b); Explanation:

Copyrights Chekuri group

www.dbakings.com
The above method add is an abstract method which is created using abstract keyword at the starting of the method signature. Signature method means the whole line present there which defines a method. It accepts two parameters and returns a value of long datatype. It has no body or implementation code. Static Method Static method is a method which can be called without any reference or object because memory for a static method is created in RAM when program is executed. Static method is a method which is created using keyword "static". Example: Addition of two numbers using static method and takes input arguments with return type using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace static_method { class Program { static void Main(string[ ] args) { long l = maths.add(4, 7); Console.WriteLine(l); Console.ReadKey(); } class maths { public static long add(int i, int j) { return i + j; } }

Copyrights Chekuri group

www.dbakings.com
} } Output: 11 Explanation: add is a method created in maths class. The method add is called in the main method directly using dot after class name as add is a static class otherwise it has to be called using object of maths class. class Class is a blue print. It is a collection of methods and member functions. In C#.NET every line of code should be in class. Class can contain variable declarations as well as initialize them at the time of declaration only.

Syntax: class classname { body } Example program using Class: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace static_method { class Program

Copyrights Chekuri group

www.dbakings.com
{ static void Main(string[] args) { maths m = new maths(); m.add(); Console.ReadKey(); } class maths { public void add() { int a = 10; int b = 20; Console.WriteLine("Addition is:"+(a + b)); } } } } Output: Addition is: 30

Object Object is an instance of class. Object will have memory. To create this object "new" keyword is used. It is a reference type. Mandatory to use the "new" keyword for creating object.

Syntax: classname objectname= new constructor;

Copyrights Chekuri group

www.dbakings.com
Example: maths m=new maths( ); Explanation: M is the name of the object created for maths class using new keyword. Maths( ) is the constructor of the class maths. Constructor will be explained later. Example program using object for a class: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace static_method { class Program { static void Main(string[] args) { maths m = new maths(); long l = m.add(3, 5); Console.WriteLine("Sum is:"+l); Console.ReadKey(); } class maths { public long add(int i,int j) { return i + j; } } } }

Copyrights Chekuri group

www.dbakings.com
Output: sum is : 8

Chapter 7

Encapsulation Encapsulation is a procedure of binding data under class name . Encapsulation is a procedure of covering up of the data & functions into a single unit called as Class. An encapsulated object is often called an abstract data type. Rather than defining the data in the form of public,we can declare those fields as private. In other words wrapping up of data and methods into a single unit is called as "Encapsulation"(ex:Class,method).

Inheritance Acquiring or getting the properties from one class to another class is known as "Inheritance". In Object Oriented approach if we can apply parent/child relation between classes. Members of the parent class can be consumed by the child classes.

Syntax: class parent { body } class child : parent { body

Copyrights Chekuri group

www.dbakings.com
} Example program: Two classes a & b with 2 methods display & show inside them with inheritance using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Inheritance { class Program { static void Main(string[] args) { b o1 = new b();//creating object for the derived class o1.show();//calling method from child class o1.display();//calling method from parent class Console.ReadKey(); } class a//parent or base class { public void display() { Console.WriteLine("display"); } } class b : a//child or derived class inherited with base class { public void show() { Console.WriteLine("show"); } } } }

Copyrights Chekuri group

www.dbakings.com
Output: show display Single Inheritance Syntax: class Parent { body } class child : parent { body } Example : using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Inheritance { class Program { static void Main(string[] args) { When a single derived class is derived from single base class,then that inheritance is called as "single inheritance". In single inheritance we have single base class that is inherited by the derived class. Here the derived class has all the features of the base class and can add some new features. The inheritance also depends on the access specifier that is used at the time of base class inheritance.

Copyrights Chekuri group

www.dbakings.com
dad d = new dad(); d.car(); son s = new son(); s.bike(); s.car(); Console.ReadKey(); } class dad { public void car() { Console.WriteLine("car"); } } class son:dad { public void bike() { Console.WriteLine("bike"); } } } }

Output: car bike car

Multi level Inheritance Acquiring properties to a subchild class from the child class and also from the parent class. When a derived class is created from another derived class,then that inheritance is called as "Multi level Inheritance".

Copyrights Chekuri group

www.dbakings.com
Syntax: class parent { body } class child : parent { body } class subchild : child { body } Example: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Inheritance { class Program { static void Main(string[] args) { grandfather g=new grandfather(); g.helicopter(); dad d = new dad(); d.car(); d.helicopter(); son s = new son(); s.bike(); s.car(); s.helicopter(); Console.ReadKey(); } class grandfather

Copyrights Chekuri group

www.dbakings.com
{ public void helicopter() { Console.WriteLine("helicopter"); } } class dad:grandfather { public void car() { Console.WriteLine("car"); } } class son : dad { public void bike() { Console.WriteLine("bike"); } } } } Output: helicopter car helicopter bike car helicopter

Hierarchial Inheritance Single parent and multiple child are called as "Hierarchial Inheritance". In other words when more than one derived class are created from single base class is called "Hierarchial Inheritance".

Copyrights Chekuri group

www.dbakings.com
Syntax: class parent { body } class child1 : parent { body } class child2 : parent { body } Example: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Inheritance { class Program { static void Main(string[] args) { grandfather g=new grandfather(); g.helicopter(); dad d = new dad(); d.helicopter(); d.car(); son s = new son(); s.helicopter(); s.bike(); Console.ReadKey(); } class grandfather {

Copyrights Chekuri group

www.dbakings.com
public void helicopter() { Console.WriteLine("helicopter"); } } class dad:grandfather { public void car() { Console.WriteLine("car"); } } class son : dad { public void bike() { Console.WriteLine("bike"); } } } } Output: helicopter helicopter car helicopter bike

Multiple Inheritance One child with two parents is known as "Multiple Inheritance". Multiple Inheritance can contain only one derived class,two or more base classes. When a derived class is created from more than one base class then that inheritance is called as"Multiple Inheritance".

Copyrights Chekuri group

www.dbakings.com
Multiple Inheritance is not supported in c# .net because due to ambiguity or confusion problem.

Syntax: class Parent { body } class parent2 { body } class child : parent,parent2 Example: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Inheritance { class Program { static void Main(string[] args) { grandfather g = new grandfather(); g.helicopter(); dad d = new dad(); d.car(); Console.ReadKey(); } class grandfather { public void helicopter() { Console.WriteLine("helicopter"); }

Copyrights Chekuri group

www.dbakings.com
} class dad { public void car() { Console.WriteLine("car"); } } class son : dad, grandfather { public void bike() { Console.WriteLine("bike"); } } } } Output: An error will occur because a class cannot have multiple base classes

Hybrid Inheritance Any combination of single, hierarchial and multi level inheritance is called as "Hybrid Inheritance". Syntax: class base class { body } class derived class : base class { body } class derived class1 : base class/derived class {

Copyrights Chekuri group

www.dbakings.com
body } Example: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Inheritance { class Program { static void Main(string[] args) { grandfather g = new grandfather(); g.helicopter(); dad d = new dad(); d.helicopter(); d.car(); son s = new son(); s.helicopter(); s.bike(); s.car(); Console.ReadKey(); } class grandfather { public void helicopter() { Console.WriteLine("helicopter"); } } class dad:grandfather { public void car() { Console.WriteLine("car");

Copyrights Chekuri group

www.dbakings.com
} } class son : dad { public void bike() { Console.WriteLine("bike"); } } } } Output: helicopter helicopter car helicopter bike car

Sealed Class A class which cannot be inherited by any other class is known as "Sealed class". It should be declared using "sealed" modifier. sealed classes are used to restrict the inheritance feature of object oriented programming. once a base class is defined as "sealedclass",this class cannot be inherited. In c#,the sealed modifier is used to define a class as "sealed". If a class is derived from a sealed class,compiler throws an error.

Syntax: sealed class classname {

Copyrights Chekuri group

www.dbakings.com
body } class classname2:classname//Invalid because derived class will not inherit sealed class. Example: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace sealed { class Program namespace sealed_class { class Program { static void Main(string[] args) { SealedClass sealedCls = new SealedClass(); int total = sealedCls.Add(4, 5); Console.WriteLine("Total = " + total.ToString()); Console.ReadKey(); } } // Sealed class sealed class SealedClass { public int Add(int x, int y) { return x + y; } } }

Copyrights Chekuri group

www.dbakings.com
Output: Total = 9 Chapter 8 Abstraction Hiding the complexity and providing the services is called "Abstraction". In other words hiding the unnecessary data and providing required facilities is called "Abstraction". ex: System.Console.ReadKey(); ReadKey() is used without writing lots of code in it. Another example is Tv remote.we can change the channels but we don't know how the inner button works.

Access Specifiers Access specifiers are also called as modifiers used to define scope of a type as well as its members ie.,who can access it and who can't access it. C# supports five different access specifiers.Those are: 1)Private 2)Public 3)Protected 4)Internal 5)Protected Internal Private Public Private can be used "Only with in the block". Members declared as private with in class or structure aren't possible outside of them in which they are defined. In C# the default scope for members of a class or structure is "Private". Where as in case of interface default is "Public".

Copyrights Chekuri group

www.dbakings.com
A type or member of a type is declared as Public,that can be accessed from "Anywhere". Protected Members declared as Protected under a class can be accessed only from child classes. Protected cannot consume non-child classes. Protected can be used "Only inherited class". Types under a namespace can't be declared as a Protected.

Internal Internal can be used "Only with in the project". Members which are declared as internal were accessible only with in the project both from child or non-child classes. The default scope for a type in C# is "Internal"only.

Protected Internal Members declared as "Protected Internal" enjoy dual scope ie.,Internal and Protected. With in the project they behave as "internal",providing access to all other classes. Outside the project they change to "Protected", and still provide access to child classes.

Creating user defined dll or namespace dll stands for "Dynamic Link Library". It is an assembly. It is a supportable file. It is also known as "namespace",which is a collection of classes. Namespaces are used in .exe files by adding them as references. Namespaces are imported using the keyword "using". Steps to create dll or namespace:

Copyrights Chekuri group

www.dbakings.com
1)Open File click on "New project". 2)under visual C# select "Windows",in that select "class Library" ,give a name as "techminds"and click on ok. 3)Then,the namespace is created with the name"techminds". 4)Using that namespace in our project and write code in it. 5)Next build "build solution"in menu or press F6. 6)Then, dll file is created in the solution and check for the location where it is stored. Steps to create exe file: 1)Open File click on"New project". 2)Under visual C# select "windows",in that select "Console appilication",give name as "techmindsexe" and click on ok. 3)Then,write the code and add reference to that. Steps to add Reference: 1)Right click on "refences" folder in "solution explorer". 2)click on "add reference". 3)click on "browse". 4)Browse the .dll file and click on ok,then the dll name will be added in the reference list. 5)Now we can add it as a namespace using the keyword "using".

Chapter 9 Polymorphism Polymorphism means "Many forms". In other words it can be defined as entities behave in different forms based on the given input ie., whenever there is a change in the input the output on behavior also changes. Polymorphism can be of two types. 1) Static Polymorphism 2) Dynamic Polymorphism 1) Static Polymorphism: It is also known as "Compile time polymorphism" .It can have same method name and different parameters. It is also known as "Method

Copyrights Chekuri group

www.dbakings.com
Overloading". 2) Dynamic Polymorphism: It is also known as "Run time polymorphism". It can have same method name and same signature. It is also known as "Method Overriding". Method Overriding can be used only when we have inheritance. Example: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace polymorphism { class Program { static void Main(string[ ] args) { y o = new y(); o.add(1, 3); Console.ReadKey(); } } class x { public void add(int a, int b) { Console.WriteLine(a + b); } } class y : x { public void add(int a, int b) {

Copyrights Chekuri group

www.dbakings.com
Console.WriteLine(a - b); } } } Output: -2 Method Overloading Method overloading is an approach which allows to define multiple methods with the same name and different signatures. Method overloading can be done within a class as well as under the child classes also. Method overloading doesn't require any permissions to overload a method from parent to child classes.

Method Overriding Method overriding is an approach which allows to define multiple methods with same name and same signatures. Method overriding can be done only under child classes. Method overloading requires an explicit permission to override a method from parent to child classes. It can be done only we have inheritance.

Abstract Method Abstract method is a method which is created using "abstract" keyword. Abstract method doesn't contain any implementation or body. In abstract method we have semicolon(;)at the end . Abstract method doesn't have curly braces. We can create abstract method only in abstract class.

Copyrights Chekuri group

www.dbakings.com
Syntax: abstract modifier void methodname(); Example: abstract public void add(); Abstract Class

Abstract class is a class created using "abstract" keyword. Abstract class can contain abstract methods and general methods. The class inheriting abstract class should implements abstract methods in that abstract class.

Syntax: abstract class classname { body } Example: abstract class a { body } Example program using abstract class and abstract method: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace abstract_class { class Program : a { static void Main(string[] args)

Copyrights Chekuri group

www.dbakings.com
{ Program p = new Program(); p.add(); p.sub(); Console.ReadKey(); } //implementing abstract method in abstract class public override void add() { Console.WriteLine("addition"); } } abstract class a { //abstract method abstract public void add(); //genaral method public void sub() { Console.WriteLine("subtraction"); } } } Output: addition subtraction Partial Class Partial class is a class which can be defined a single class in multiple files,when compilation time these classes are combined to form a single class. Partial classes can be defined with the keyword "partial". All the Partial classes must have the same accessibility. If any part is declared as "sealed",the entire class is sealed. If any part is declared as "abstract",the entire class is abstract.

Copyrights Chekuri group

www.dbakings.com
Method signatures must be unique for the types which are defined partially.

Copyrights Chekuri group

Você também pode gostar