oops pramming with examples

43
I have created a sample console application which lists all oops related examples like types,inheritence ,interface,sealed,delegates,enum,threading,linq,re gular expressions,extension methods,generics,arrays,list...so on. just copy and run your application in console and see the output.. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace CSharpAndMe { class Program { enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat }; static void Main(string[] args) { // Derived d = new Base(); Base b = new Derived(); b.print(); b.display(); Derived d1 = new Derived(); d1.display(); //TODO: understanding string type //Defination: Nearly every program uses strings.

Upload: syed-khaleel

Post on 16-Apr-2017

135 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Oops pramming with examples

I have created a sample console application which lists all oops related examples like types,inheritence ,interface,sealed,delegates,enum,threading,linq,regular expressions,extension methods,generics,arrays,list...so on.

just copy and run your application in console and see the output..

using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Text.RegularExpressions;using System.Threading;using System.Threading.Tasks;

namespace CSharpAndMe{ class Program { enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

static void Main(string[] args) {

// Derived d = new Base();

Base b = new Derived(); b.print(); b.display(); Derived d1 = new Derived(); d1.display();

//TODO: understanding string type //Defination: Nearly every program uses strings. //In strings, we find characters, words and textual data. The string type allows us to test and manipulate character data. //There are different ways to build and format strings in C#: concatenation, numeric format strings, or string interpolation. //Note : The string keyword is an alias for the System.String class. //from string literal and string concatenation Console.WriteLine("------------String---------------------------"); string fname, lname; fname = "Syed";

Page 2: Oops pramming with examples

lname = "Khaleel";

string fullname = fname + lname; Console.WriteLine("Full Name: {0}", fullname);

//by using string constructor char[] letters = { 'H', 'e', 'l', 'l', 'o' }; string greetings = new string(letters); Console.WriteLine("Greetings: {0}", greetings);

//methods returning string string[] sarray = { "Hello", "From", "Tutorials", "Point" }; string message = String.Join(" ", sarray); Console.WriteLine("Message: {0}", message);

//formatting method to convert a value DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format("Message sent at {0:t} on {0:D}", waiting); Console.WriteLine("Message: {0}", chat);

//TODO: Nullable type //Defination: C# provides a special data types, the nullable types, //to which you can assign normal range of values as well as null values. Console.WriteLine("------------Nullable Type----------------------"); int? num1 = null; int? num2 = 45; double? num3 = new double?(); double? num4 = 3.14157;

bool? boolval = new bool?(); // display the values

Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", num1, num2, num3, num4); Console.WriteLine("A Nullable boolean value: {0}", boolval);

//TODO: Implementing enum data type //Defination: 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. Console.WriteLine("--------------------Enum type------------------------------"); int WeekdayStart = (int)Days.Mon; int WeekdayEnd = (int)Days.Fri; Console.WriteLine("Monday: {0}", WeekdayStart); Console.WriteLine("Friday: {0}", WeekdayEnd);

Page 3: Oops pramming with examples

//TODO: Regular Expression //Defination: A regular expression is a pattern that could be matched against an input text. //The .Net framework provides a regular expression engine that allows such matching. //A pattern consists of one or more character literals, operators, or constructs. Console.WriteLine("---------------------Regulare Expression----------------------------"); string str = "A Thousand Splendid Suns"; Console.WriteLine("Matching words that start with 'S': "); showMatch(str, @"\bS\S*");

str = "make maze and manage to measure it"; Console.WriteLine("Matching words start with 'm' and ends with 'e':"); showMatch(str, @"\bm\S*e\b");

//TODO: Remove Duplicate characters from a string Console.WriteLine("Removing Duplicates from a string"); Console.WriteLine( RemoveDuplicates("abcddeeffgghii"));

//TODO: Extension method //Defination: extension method is a static method of a static class that can be invoked using the instance method syntax. //Extension methods are used to add new behaviors to an existing type without altering. //In extension method "this" keyword is used with the first parameter and the type of the first //parameter will be the type that is extended by extension method. Console.WriteLine("---------------------------------Extension Method-----------------------------------"); string _s = "Dot Net Extension Method Example"; //calling extension method int _i = _s.WordCount(); Console.WriteLine(_i); //TODO: Implementing Simple If condition //Defination: If statement consists of Boolean expression followed by single or multiple statements to execute. //An if statement allows you to take different paths of logic, depending on a given condition. //When the condition evaluates to a boolean true, a block of code for that true condition will execute. //You have the option of a single if statement, multiple else if statements, and an optional else statement. Console.WriteLine("---------------------------------- If Condition--------------------------------------"); int age = 20;

Page 4: Oops pramming with examples

string Name = "Syed Khaleel"; if (age < 18) { Console.WriteLine("{0} is Minor", Name); } else { Console.WriteLine("{0} is Major", Name); } //TODO :Implementing for loop. //Defination: A for loop is a repetition control structure that allows you to efficiently write a loop //that needs to execute a specific number of times. Console.WriteLine("-------------For Loop----------------"); for (int i = 1; i <= 10; i++) { Console.Write(i + " "); } Console.WriteLine(); //TODO :While loop //Defination: It repeats a statement or a group of statements while a given condition is true. //It tests the condition before executing the loop body. Console.WriteLine("-------------While Loop-------------"); int j = 1; while (j <= 10) { Console.Write(j + " "); j++; } Console.WriteLine();

//TODO : Do while //Defination: It is similar to a while statement, except that it tests the condition at the end of the loop body Console.WriteLine("----------------Do While----------------"); int x = 1; do { Console.Write(x + " "); x++; } while (x <= 10);

Console.WriteLine();

//TODO : Foreach //loops through the collection of items or objects

Page 5: Oops pramming with examples

Console.WriteLine("--------------Foreach----------------"); string[] arr = { "sd", "md", "kd" }; foreach (var item in arr) { Console.Write(item + " "); } Console.WriteLine();

//TODO: Implementing Loop Control Statement with break. //Defination: Terminates the loop or switch statement and transfers execution //to the statement immediately following the loop or switch.

/* local variable definition */ int a = 1;

/* while loop execution */ while (a < 15) { Console.WriteLine("value of a: {0}", a); a++; if (a > 10) { /* terminate the loop using break statement */ break; } }

//TODO: Implementing Loop Contorl Statemnet with Continue. //Defination: Causes the loop to skip the remainder of its body and immediately //retest its condition prior to reiterating. //Note*:The continue statement in C# works somewhat like the break statement. //Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between. Console.WriteLine("--------------------Loop Control Statement---------------------------------"); /* local variable definition */ int value = 10; /* do loop execution */ do { if (value == 15) { /* skip the iteration */ value = value + 1; continue; } Console.WriteLine("value of a: {0}", value); value++;

Page 6: Oops pramming with examples

} while (value < 20);

//TODO : switch //Defination: A switch statement allows a variable to be tested for equality against a list of values. //Each value is called a case, and the variable being switched on is checked for each switch case. var color = "Red"; Console.WriteLine("----------------Swith Case----------------"); switch (color) { case "Red": Console.WriteLine("Color in Color is " + color); break; case "Pink": Console.WriteLine("Color in Color is " + color); break; case "Yellow": Console.WriteLine("Color in Color is " + color); break; default: break; }

//TODO: single dimensional array //Defination: An array stores a fixed-size sequential collection of elements of the same type. //An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type //stored at contiguous memory locations.

int n = int.Parse("855"); int d = 0; string res = ""; string[] ones = new string[] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; string[] tens = new string[] { "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninty" }; Console.WriteLine("------------Singe Dimensional Array-----------------");

if (n > 99 && n < 1000) { d = n / 100; res = ones[d - 1] + "Hundred"; n = n % 100; }

Page 7: Oops pramming with examples

if (n > 19 && n < 100) { d = n / 10; res = res + tens[d - 1]; n = n % 10; } if (n > 0 && n < 10) { res = res + ones[n - 1]; } Console.WriteLine(res); Console.WriteLine("--------------Multi Dimensional Array---------------------");

//TODO : multi dimensional array //Defination: stores data in rows and columns string s = ""; int[,] xx = new int[,] { {7,8,9,0}, {1,2,3,4}, {9,9,9,9} }; for (int r = 0; r < xx.GetLength(0); r++) { for (int c = 0; c < xx.GetLength(1); c++) { s = s + xx[r, c] + " "; } Console.WriteLine(s + " "); s = ""; } Console.WriteLine("--------------------Jagged Array--------------------"); //TODO : jagged array //Defination: Its an array of array of differenct sizes int[][] xxx = new int[3][]; xxx[0] = new int[] { 1, 2, 3, }; xxx[1] = new int[] { 10, 20, 30 }; xxx[2] = new int[] { 1, 2, 3, }; string sss = ""; for (int r = 0; r < xxx.GetLength(0); r++) { for (int c = 0; c < xxx.GetLength(0); c++) { sss = sss + xxx[r][c] + " "; } sss = sss + "\n"; } Console.Write(sss);

Page 8: Oops pramming with examples

//TODO: Collections using ArrayList //Defination: It represents an ordered collection of an object that can be indexed individually. //It is basically an alternative to an array. However, unlike array you can add and remove items //from a list at a specified position using an index and the array resizes itself automatically. //It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList al = new ArrayList(); Console.WriteLine("Adding some numbers:"); al.Add(45); al.Add(78); al.Add(33); al.Add(56); al.Add(12); al.Add(23); al.Add(9);

Console.WriteLine("Capacity: {0} ", al.Capacity); Console.WriteLine("Count: {0}", al.Count); Console.Write("Content: "); foreach (int i in al) { Console.Write(i + " "); }

Console.WriteLine(); Console.Write("Sorted Content: "); al.Sort(); foreach (int i in al) { Console.Write(i + " "); } Console.WriteLine(); //TODO: Generics //Defincation:Generics allow you to delay the specification of the data type of programming elements in a class or a method, //until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type. //declaring an int array MyGenericArray<int> intArray = new MyGenericArray<int>(5); //setting values for (int c = 0; c < 5; c++) { intArray.setItem(c, c * 5); } //retrieving the values

Page 9: Oops pramming with examples

for (int c = 0; c < 5; c++) { Console.Write(intArray.getItem(c) + " "); } Console.WriteLine(); //declaring a character array MyGenericArray<char> charArray = new MyGenericArray<char>(5); //setting values for (int c = 0; c < 5; c++) { charArray.setItem(c, (char)(c + 97)); } //retrieving the values for (int c = 0; c < 5; c++) { Console.Write(charArray.getItem(c) + " "); } Console.WriteLine();

//TODO: Constructor //Defination: A constructor is a method of the class, //i.e. meant for initializing the data members. The constructor gets called automatically, whenever the object is declared. Sample obj1 = new Sample(new Sample() { EmpId = 51581, ENmae = "Syed Khaleel", EAdress = "Hyd", EAge = 29 }); obj1.displayEmpData();

//calling paramterized consturctor ClsEmployee5 obj11 = new ClsEmployee5(121, "Syed Khaleel", "Hyd", 22); obj11.DisplayEmpdata();

//TODO: calling constructor overloading ClsConstrutorOverloading obj111 = new ClsConstrutorOverloading(101, "Syed Khaleel", "Hyd", 24); ClsConstrutorOverloading obj2 = new ClsConstrutorOverloading(102, "Anand"); obj111.DisplayEmpData(); obj2.DisplayEmpData();

//TODO:calculate salary

ClsSalary objsal = new ClsSalary(); objsal.GetSalData();

Page 10: Oops pramming with examples

objsal.Calculate(); objsal.DisplaySqldata();

//TODO: user defined defualt constructor UserDefinedDefualtConstructor UserDefinedDefualtConstructor = new UserDefinedDefualtConstructor(); UserDefinedDefualtConstructor.DisplayEmpData();

//TODO : Invoking class inherited from Abstract class. Square square = new Square(); Console.WriteLine("--------------------Abstract Class--------------------"); Console.WriteLine(square.Area());

//TODO: Multiple Inheritence Console.WriteLine("--------------------------Multiple Inheritence with Interface-------------------"); Manager manager = new Manager(); manager.GetBData(); manager.GetEmpData(); manager.DisplayBData(); manager.DisplayEmpData();

//TODO: Implementing Interface //Defination: An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. //The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract. //consists of only abstract memebers,by defualt members are public. Console.WriteLine("--------------------------------Interface Example--------------------------"); I1 I = new C3(); I.F1(); I2 I2 = new C3(); I2.F1(); C3 c3 = new C3(); c3.F1();

//TODO: Properties //Defination: Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. //Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written or manipulated Console.WriteLine("------------------------------- Properties ----------------------------------"); Property_Employee Property_Employee = new Property_Employee(); Console.Write("Enter Employee Details Id,Name,Address,Age"); Property_Employee.PEmpId = Convert.ToInt32(Console.ReadLine()); Property_Employee.PEName = Console.ReadLine(); Property_Employee.PEAddress = Console.ReadLine();

Page 11: Oops pramming with examples

Property_Employee.PEAge = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(" Employee Id is " + Property_Employee.PEmpId); Console.WriteLine(" Employee Name is " + Property_Employee.PEName); Console.WriteLine(" Employee Address is " + Property_Employee.PEAddress); Console.WriteLine(" Employee Age is " + Property_Employee.PEAge);

//TODO : Implementing Arrays Console.WriteLine("----------------------------Reading Names from String Array --------------------"); string[] A = new string[6] { "Syed", "Raheem", "Anand", "Bela", "Pravesh", "Krishna" }; Console.WriteLine("ELEMENT of ARRAY array"); for (int i = 0; i < 6; i++) { Console.WriteLine(A[i] + ""); }

//TODO: Sealed Class //Defination: a sealed class is a class which cannot be derived from other class. Console.WriteLine("------------------------Sealed Class--------------------"); clsmanager obj = new clsmanager(); obj.GetEmpdata(); obj.DisplayEmpData();

//TODO: Partial Class Implemention //Defination:a class can be divided into multiple classes using partial keyword. Console.WriteLine("-------------------Partial Class------------------------------"); PartialClsEmployee PartialClsEmployee = new PartialClsEmployee(); PartialClsEmployee.Getempdata(); PartialClsEmployee.DisplayEmpdata();

//TODO: Delegate Console.WriteLine("--------------------Delegate-----------------------------"); DelegateDemo delDemo = new DelegateDemo(); CSharpAndMe.Program.DelegateDemo.sayDel sd = new CSharpAndMe.Program.DelegateDemo.sayDel(delDemo.sayHello); Console.WriteLine(sd("xxx")); CSharpAndMe.Program.DelegateDemo.addDel ad = new CSharpAndMe.Program.DelegateDemo.addDel(delDemo.add); ad(10, 20);

//TODO: Exceptional Handling //Defination: 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. Console.WriteLine("-----------------Exceptional Handling-------------------------"); ExceptionExample ExceptionExample = new ExceptionExample();

Page 12: Oops pramming with examples

ExceptionExample.divide();

//TODO: Implementing Structures //Defination: 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. Console.WriteLine("------------------- Structures ----------------------------------"); MyStruct m1; // invokes default constructor m1.x = 100; m1.show(); Console.WriteLine(m1.x); MyStruct m2 = new MyStruct(200); m2.show(); Console.WriteLine(m2.x);

//The acronym LINQ is for Language Integrated Query. Microsoft’s query language is fully integrated and offers easy data access from in-memory objects, //databases, XML documents and many more. It is through a set of extensions, LINQ ably integrate queries in C# and Visual Basic.

//TODO: Linq Example ,finding no of files with same file extension. Console.WriteLine("------------------ Linq Example ---------------------------"); string[] arrfile = { "aaa.txt", "bbb.TXT", "xyz.abc.pdf", "aaaa.PDF", "abc.xml", "ccc.txt", "zzz.txt" }; var egrp = arrfile.Select(file => Path.GetExtension(file).TrimStart('.').ToLower()) .GroupBy(item => item, (ext, extCnt) => new { Extension = ext, Count = extCnt.Count(), });

foreach (var v in egrp) Console.WriteLine("{0} File(s) with {1} Extension ", v.Count, v.Extension);

//TODO: Linq, find the file size Console.WriteLine("-------------------- Find file size using LINQ -----------------------"); string[] dirfiles = Directory.GetFiles("E:\\Docs\\");//change the location if var avg = dirfiles.Select(file => new FileInfo(file).Length).Average(); avg = Math.Round(avg / 10, 1); Console.WriteLine("The Average file size is {0} MB", avg);

//TODO: Generate Odd Numbers using LINQ Console.WriteLine("-------------Linq to generate Odd Numbers in Parallel------------------"); IEnumerable<int> oddNums = ((ParallelQuery<int>)ParallelEnumerable.Range(20, 2000)) .Where(m => m % 2 != 0).OrderBy(m => m).Select(i => i); foreach (int m in oddNums) {

Page 13: Oops pramming with examples

Console.Write(m + " "); }

//TODO: Linq using IEnumareble Console.WriteLine("------------------------ IEnumareble using LINQ ------------------------"); var t = typeof(IEnumerable); var typesIEnum = AppDomain.CurrentDomain.GetAssemblies().SelectMany(ii => ii.GetTypes()).Where(ii => t.IsAssignableFrom(ii)); var count = 0; foreach (var types in typesIEnum) { Console.WriteLine(types.FullName); count++; if (count == 20) break; } //TODO: Divide numbers in sequence using Linq and Enumarable Console.WriteLine("-------------------- C# Program to Divide Sequence into Groups using LINQ ------------------------------"); var seq = Enumerable.Range(100, 100).Select(ff => ff / 10f); var grps = from ff in seq.Select((k, l) => new { k, Grp = l / 10 }) group ff.k by ff.Grp into y select new { Min = y.Min(), Max = y.Max() }; foreach (var grp in grps) Console.WriteLine("Min: " + grp.Min + " Max:" + grp.Max);

//TODO : get Student Details using linq Program pg = new Program(); IEnumerable<Student> studentQuery1 = from student in pg.students where student.ID > 1 select student;

Console.WriteLine("Query : Select range_variable"); Console.WriteLine("Name : ID"); foreach (Student stud in studentQuery1) { Console.WriteLine(stud.ToString()); }

//TODO: get numbers above 500 using linq int[] numbers = { 500, 344, 221, 4443, 229, 1008, 6000, 767, 256, 10,501 }; var greaterNums = from num in numbers where num > 500 select num;

Page 14: Oops pramming with examples

Console.WriteLine("Numbers Greater than 500 :"); foreach (var gn in greaterNums) { Console.Write(gn.ToString() + " "); }

//Object Initialization for Student class List<Students> objStudent = new List<Students>{ new Students{ Name="Tom",Regno="R001",Marks=80}, new Students{ Name="Bob",Regno="R002",Marks=40}, new Students{ Name="jerry",Regno="R003",Marks=25}, new Students{ Name="Syed",Regno="R004",Marks=30}, new Students{ Name="Mob",Regno="R005",Marks=70}, };

var objresult = from stu in objStudent let totalMarks = objStudent.Sum(mark => mark.Marks) let avgMarks = totalMarks / 5 where avgMarks > stu.Marks select stu; foreach (var stu in objresult) { Console.WriteLine("Student: {0} {1}", stu.Name, stu.Regno); }

//TODO: Binary to decimal conversion

int numm, binary_val, decimal_val = 0, base_val = 1, rem; Console.Write("Enter a Binary Number(1s and 0s) : "); numm = int.Parse(Console.ReadLine()); /* maximum five digits */ binary_val = numm; while (numm > 0) { rem = numm % 10; decimal_val = decimal_val + rem * base_val; numm = numm / 10; base_val = base_val * 2; } Console.Write("The Binary Number is : " + binary_val); Console.Write("\nIts Decimal Equivalent is : " + decimal_val);

//TODO: Implementing Threading, simple thread Program prog = new Program(); Thread thread = new Thread(new ThreadStart(prog.WorkThreadFunction)); thread.Start(); Console.Read();

//TODO: Implementing thread pool

Page 15: Oops pramming with examples

ThreadPoolDemo tpd = new ThreadPoolDemo(); for (int i = 0; i < 2; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback(tpd.task1)); ThreadPool.QueueUserWorkItem(new WaitCallback(tpd.task2)); }

//TODO: Implementing thread sleep for (int i = 0; i < 5; i++) { Console.WriteLine("Sleep for 2 Seconds"); Thread.Sleep(2000); } for (int i = 0; i < 10; i++) { ThreadStart start = new ThreadStart(TEST); new Thread(start).Start(); }

ThreadingClass th = new ThreadingClass(); Thread thread1 = new Thread(th.DoStuff); thread1.Start(); Console.WriteLine("Press any key to exit!!!"); Console.ReadKey(); th.Stop(); thread1.Join();

//mathematical programs //TODO: Generating Febonaci Series Console.WriteLine("Febonaci Series"); int fi, _count, f1 = 0, f2 = 1, f3 = 0; Console.Write("Enter the Limit : "); _count = int.Parse(Console.ReadLine()); Console.WriteLine(f1); Console.WriteLine(f2); for (fi = 0; fi <= _count; fi++) { f3 = f1 + f2; Console.WriteLine(f3); f1 = f2; f2 = f3; }

//Factorial of given number Console.WriteLine("Factorial of a Number"); int faci, number, fact; Console.WriteLine("Enter the Number");

Page 16: Oops pramming with examples

number = int.Parse(Console.ReadLine()); fact = number; for (faci = number - 1; faci >= 1; faci--) { fact = fact * faci; } Console.WriteLine("\nFactorial of Given Number is: " + fact);

//Armstrong Number //TODO: Finding Armstrong Number Console.WriteLine("Armstrong Number"); int numberr, remainder, sum = 0; Console.Write("enter the Number"); numberr = int.Parse(Console.ReadLine()); for (int i = numberr; i > 0; i = i / 10) { remainder = i % 10; sum = sum + remainder * remainder * remainder; } if (sum == numberr) { Console.Write("Entered Number is an Armstrong Number"); } else Console.Write("Entered Number is not an Armstrong Number");

//Perfect Number //TODO: Perfect Number Example Console.WriteLine("Perfect Number");

int numberrr, summ = 0, nn; Console.Write("enter the Number"); numberrr = int.Parse(Console.ReadLine()); nn = numberrr; for (int i = 1; i < numberrr; i++) { if (numberrr % i == 0) { summ = summ + i; } } if (summ == nn) { Console.WriteLine("\n Entered number is a perfect number"); Console.ReadLine(); } else

Page 17: Oops pramming with examples

{ Console.WriteLine("\n Entered number is not a perfect number"); Console.ReadLine(); }

//Palindrom //TODO: to find the palindrome of a number Console.WriteLine("Palindrome of a given number"); int _num, temp, remainderr, reverse = 0; Console.WriteLine("Enter an integer \n"); _num = int.Parse(Console.ReadLine()); temp = _num; while (_num > 0) { remainderr = _num % 10; reverse = reverse * 10 + remainderr; _num /= 10; } Console.WriteLine("Given number is = {0}", temp); Console.WriteLine("Its reverse is = {0}", reverse); if (temp == reverse) Console.WriteLine("Number is a palindrome \n"); else Console.WriteLine("Number is not a palindrome \n");

//TODO: finding Distance using time and speed Console.WriteLine("Distance Travelled in Time and speed"); int speed, distance, time; Console.WriteLine("Enter the Speed(km/hr) : "); speed = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the Time(hrs) : "); time = Convert.ToInt32(Console.ReadLine()); distance = speed * time; Console.WriteLine("Distance Travelled (kms) : " + distance);

Console.WriteLine("Prime Number");

Console.Write("Enter a Number : "); int nummm; nummm = Convert.ToInt32(Console.ReadLine()); int _k; _k = 0; for (int i = 1; i <= nummm; i++) { if (nummm % i == 0) { _k++; }

Page 18: Oops pramming with examples

} if (_k == 2) { Console.WriteLine("Entered Number is a Prime Number and the Largest Factor is {0}", nummm); } else { Console.WriteLine("Not a Prime Number"); }

abbrevation _abrevation = new abbrevation(); _abrevation.readdata(); _abrevation.abbre();

//Reverse of a string

string Str, reversestring = ""; int Length; Console.Write("Enter A String : "); Str = Console.ReadLine(); Length = Str.Length - 1; while (Length >= 0) { reversestring = reversestring + Str[Length]; Length--; } Console.WriteLine("Reverse String Is {0}", reversestring);

//TODO: Create a File //Defination: A file is a collection of data stored in a disk with a specific name and a directory path. //When a file is opened for reading or writing, it becomes a stream. //The stream is basically the sequence of bytes passing through the communication path. //There are two main streams: the input stream and the output stream. //The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation). string textpath = @"E:\Docs\test.txt"; using (FileStream fs = File.Create(textpath)) { Byte[] info = new UTF8Encoding(true).GetBytes("File is Created"); fs.Write(info, 0, info.Length); } using (StreamReader sr = File.OpenText(textpath)) { string sentence = ""; while ((sentence = sr.ReadLine()) != null)

Page 19: Oops pramming with examples

{ Console.WriteLine(sentence); } }

FileRead fr = new FileRead(); fr.readdata();

Console.ReadKey(); }

private static void showMatch(string text, string expr) { Console.WriteLine("The Expression: " + expr); MatchCollection mc = Regex.Matches(text, expr); foreach (Match m in mc) { Console.WriteLine(m); } }

public static string RemoveDuplicates(string input) { return new string(input.ToCharArray().Distinct().ToArray()); }

//TODO : copy constructor class Sample { public int EmpId, EAge; public string ENmae, EAdress; public Sample() { //Console.WriteLine("------------Enter Employee Details EmployeeId,Name,Address,Age---------------------"); //EmpId = Convert.ToInt32(Console.ReadLine()); //ENmae = Console.ReadLine(); //EAdress = Console.ReadLine(); //EAge = Convert.ToInt32(Console.ReadLine()); }

public Sample(Sample objTemp) { EmpId = objTemp.EmpId; ENmae = objTemp.ENmae; EAdress = objTemp.EAdress; EAge = objTemp.EAge; }

Page 20: Oops pramming with examples

public void displayEmpData() { Console.WriteLine("-------------------------Parameterized Constructor Passing an Object-------------------------"); Console.WriteLine("Employee Id is " + EmpId); Console.WriteLine("Employee ENmae is " + ENmae); Console.WriteLine("Employee Adress is " + EAdress); Console.WriteLine("Employee Age is " + EAge); } } //TODO: parameterized consturctor class ClsEmployee5 { int EmpId, EAge; string ENmae, EAddress; public ClsEmployee5(int Id, string S1, string S2, int Ag) { this.EmpId = Id; this.ENmae = S1; this.EAddress = S2; this.EAge = Ag; } public void DisplayEmpdata() { Console.WriteLine("------------------------------Parameterized Constructor----------------------------------------"); Console.WriteLine("Employee Id is " + EmpId); Console.WriteLine("Employee Name is " + ENmae); Console.WriteLine("Employee Address is " + EAddress); Console.WriteLine("Employee Age is " + EAge); } }

//TODO: constructor overloading class ClsConstrutorOverloading { int EmpId, EAge; string EName, EAddress; public ClsConstrutorOverloading() { EmpId = 101; EName = "Syed"; EAddress = "Hyd"; EAge = 24;

} public ClsConstrutorOverloading(int Id, string S1) {

Page 21: Oops pramming with examples

EmpId = Id; EName = S1; } public ClsConstrutorOverloading(int Id, string S1, string S2, int Ag) { EmpId = Id; EName = S1; EAddress = S2; EAge = Ag; } public void DisplayEmpData() { Console.WriteLine("---------------------------------- Constructor Overloading --------------------------------------------------"); Console.WriteLine("Employee id is " + EmpId); Console.WriteLine("Employee Name is " + EName); Console.WriteLine("Employee Adress is " + EAddress); Console.WriteLine("Employee Age is " + EAge); } }

class ClsSalary { int EmpId; string Ename; double basic, Da, Hra, Gross; public void GetSalData() { Console.WriteLine("------------------ Salary --------------------------"); Console.Write("Enter Employee details Employee Id,Name,Basic"); this.EmpId = Convert.ToInt32(Console.ReadLine()); this.Ename = Console.ReadLine(); this.basic = Convert.ToDouble(Console.ReadLine()); } public void Calculate() { this.Da = 0.4 * this.basic; this.Hra = 0.3 * this.basic; this.Gross = this.basic + this.Da + this.Hra; } public void DisplaySqldata() { Console.WriteLine("Employee Id is " + this.EmpId); Console.WriteLine("Employee Nameis " + this.Ename); Console.WriteLine("Employee basic is " + this.basic); Console.WriteLine("Employee da is " + this.Da); Console.WriteLine("Employee hra is " + this.Hra); Console.WriteLine("Employee Gross is " + this.Gross);

Page 22: Oops pramming with examples

} }

//Userdefined default Constructor class UserDefinedDefualtConstructor { int EmpId, Age; string EName, EAddress; public UserDefinedDefualtConstructor() { this.EmpId = 101; this.EName = "Syed Khaleel"; this.EAddress = "Hyd"; this.Age = 25; } public void DisplayEmpData() { Console.WriteLine("--------------------------User defined default Constructor-----------------------------------------"); Console.WriteLine("EmpId is " + EmpId); Console.WriteLine("Employee Name " + EName); Console.WriteLine("Employee EADDRESS " + EAddress); Console.WriteLine("Employee AGE " + Age); } }

// TODO : abstract class //Defination: An Abstract class is an incomplete class or special class we can't instantiate. //We can use an Abstract class as a Base Class. An Abstract method must be implemented in the non-Abstract class using the override keyword. //After overriding the abstract method is in the non-Abstract class. //We can derive this class in another class and again we can override the same abstract method with it. abstract class ShapesClass { abstract public int Area(); } class Square : ShapesClass { int x = 10, y = 20; // Not providing an Area method results // in a compile-time error. public override int Area() { return x * y; } }

Page 23: Oops pramming with examples

class Branch { int Bcode; string BName, BAddress; public void GetBData() { Console.WriteLine("Enter Branch Details Code,Name,Address"); Bcode = Convert.ToInt32(Console.ReadLine()); BName = Console.ReadLine(); BAddress = Console.ReadLine(); } public void DisplayBData() { Console.WriteLine(" Branch Code is " + Bcode); Console.WriteLine(" Branch BName is " + BName); Console.WriteLine(" Branch BAddress is " + BAddress); } } interface Employee { void GetEmpData(); void DisplayEmpData(); } class Manager : Branch, Employee { int EmpId; string EName; double Bonus, CA; public void GetEmpData() { Console.WriteLine("Enter Manager Details Id,Name,Bonus,CA"); EmpId = Convert.ToInt32(Console.ReadLine()); EName = Console.ReadLine(); Bonus = Convert.ToDouble(Console.ReadLine()); CA = Convert.ToDouble(Console.ReadLine()); } public void DisplayEmpData() { Console.WriteLine("Manager id is " + EmpId); Console.WriteLine("Manager Name is " + EName); Console.WriteLine("Manager Bonus is " + Bonus); Console.WriteLine("Manager CA is " + CA); } }

interface I1 {

Page 24: Oops pramming with examples

void F1(); } interface I2 { void F1(); } class C3 : I1, I2 { void I1.F1() { Console.WriteLine("Method f1 from I1"); }

void I2.F1() { Console.WriteLine("Method F2 from I2"); }

public void F1() { Console.WriteLine("F1 of C3"); } }

//TODO : c# Properties example //Definatio: On a class, a property gets and sets values. A simplified syntax form, properties are implemented in the IL as methods. //Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. //Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, //written or manipulated

class Property_Employee { int EmpId, EAge; string EName, EAddress; public int PEmpId { set { EmpId = value; } get { return EmpId; }

} public int PEAge { set { EAge = value; } get { return EAge; } }

Page 25: Oops pramming with examples

public string PEName { set { EName = value; } get { return EName; } } public string PEAddress { set { EAddress = value; } get { return EAddress; } } }

//TODO: Sealed Class

class ClsEmployee { protected int Empid; int Eage; protected string Ename; string Eaddress; public virtual void GetEmpdata() { Console.Write("Enter Empliyee Details Id,Name,Address,Age:-"); this.Empid = Convert.ToInt32(Console.ReadLine()); this.Ename = Console.ReadLine(); this.Eaddress = Console.ReadLine(); this.Eage = Convert.ToInt32(Console.ReadLine()); } public virtual void DisplayEmpData() { Console.WriteLine("Employee id is:-" + this.Empid); Console.WriteLine("Employee id is:-" + this.Ename); Console.WriteLine("Employee id is:-" + this.Eaddress); Console.WriteLine("Employee id is:-" + this.Eage); } } sealed class clsmanager : ClsEmployee { double bonus, ca; public override void GetEmpdata() { Console.Write("Enter Empliyee Details Id,Name,Bonus,CA:-"); Empid = Convert.ToInt32(Console.ReadLine()); Ename = Console.ReadLine(); bonus = Convert.ToDouble(Console.ReadLine()); ca = Convert.ToDouble(Console.ReadLine()); } public override void DisplayEmpData() { Console.WriteLine("Manager id is:-" + Empid);

Page 26: Oops pramming with examples

Console.WriteLine("Manager name is:-" + Ename); Console.WriteLine("Manager bonus is:-" + bonus); Console.WriteLine("Manager ca is:-" + ca);

} }

//TODO: Partial Class

partial class PartialClsEmployee { int empid, eage; string ename, eaddress; public void Getempdata() { Console.WriteLine("Enter Employee details Id,Name,Address,Age"); this.empid = Convert.ToInt32(Console.ReadLine()); this.ename = Console.ReadLine(); this.eaddress = Console.ReadLine(); this.eage = Convert.ToInt32(Console.ReadLine()); } }

partial class PartialClsEmployee { public void DisplayEmpdata() { Console.WriteLine("Employee id is:-" + empid); Console.WriteLine("Employee name is:-" + ename); Console.WriteLine("Employee address is:-" + eaddress); Console.WriteLine("Employee id is:-" + eage); } } //TODO: Exception Handling //Defination: 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. public class ExceptionExample { int x, y, z;

public void divide() { try { Console.WriteLine("enter x value : "); x = int.Parse(Console.ReadLine()); Console.WriteLine("enter y value : "); y = int.Parse(Console.ReadLine());

Page 27: Oops pramming with examples

z = x / y; Console.WriteLine(z); }

catch (DivideByZeroException ex1) { Console.WriteLine("Divider should not be zero"); } catch (FormatException ex2) { Console.WriteLine("u r entered wrong format"); } catch (Exception e) { Console.WriteLine("error occured"); } Console.WriteLine("end of the program"); Console.ReadLine(); } }

//TODO:Delegates //Defination: 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. class DelegateDemo { public delegate string sayDel(string name); public delegate void addDel(int x, int y);

public string sayHello(string name) { return "Hello" + name; } public void add(int x, int y) { Console.WriteLine(x + y); } }

//TODO: Structures //Defination: 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. struct MyStruct {

Page 28: Oops pramming with examples

public int x; public MyStruct(int x) { this.x = x; } public void show() { Console.WriteLine("Method in structure : " + x); } }

// TODO : to get Student Details using LINQ...

public class Student { public string First { get; set; } public string Last { get; set; } public int ID { get; set; } public List<int> Marks;

public ContactInfo GetContactInfo(Program pg, int id) { ContactInfo allinfo = (from ci in pg.contactList where ci.ID == id select ci) .FirstOrDefault();

return allinfo; }

public override string ToString() { return First + "" + Last + " : " + ID; } }

public class ContactInfo { public int ID { get; set; } public string Email { get; set; } public string Phone { get; set; } public override string ToString() { return Email + "," + Phone; } }

public class ScoreInfo { public double Average { get; set; }

Page 29: Oops pramming with examples

public int ID { get; set; } } List<Student> students = new List<Student>() { new Student {First="Tom", Last=".S", ID=1, Marks= new List<int>() {97, 92, 81, 60}}, new Student {First="Jerry", Last=".M", ID=2, Marks= new List<int>() {75, 84, 91, 39}}, new Student {First="Bob", Last=".P", ID=3, Marks= new List<int>() {88, 94, 65, 91}}, new Student {First="Mark", Last=".G", ID=4, Marks= new List<int>() {97, 89, 85, 82}}, }; List<ContactInfo> contactList = new List<ContactInfo>() { new ContactInfo {ID=111, Email="[email protected]", Phone="9328298765"}, new ContactInfo {ID=112, Email="[email protected]", Phone="9876543201"}, new ContactInfo {ID=113, Email="[email protected]", Phone="9087467653"}, new ContactInfo {ID=114, Email="[email protected]", Phone="9870098761"} }; class Students { public string Name { get; set; } public string Regno { get; set; } public int Marks { get; set; } } class ThreadPoolDemo { public void task1(object obj) { for (int i = 0; i <= 2; i++) { Console.WriteLine("Task 1 is being executed"); } } public void task2(object obj) { for (int i = 0; i <= 2; i++) { Console.WriteLine("Task 2 is being executed"); } } } static readonly object _object = new object(); static void TEST() { lock (_object) { Thread.Sleep(100); Console.WriteLine(Environment.TickCount);

Page 30: Oops pramming with examples

} } public class ThreadingClass { private bool flag = false; private int count = 0; public void DoStuff() { while (!flag) { Console.WriteLine(" Thread is Still Working"); Thread.Sleep(1000); count++; if (count == 20) break;

} } public void Stop() { flag = true; } } public class abbrevation { string str; public void readdata() { Console.WriteLine("Enter a String :"); str = Console.In.ReadLine(); } public void abbre() { char[] c, result; int j = 0; c = new char[str.Length]; result = new char[str.Length]; c = str.ToCharArray(); result[j++] = (char)((int)c[0] ^ 32); result[j++] = '.'; for (int i = 0; i < str.Length - 1; i++) { if (c[i] == ' ' || c[i] == '\t' || c[i] == '\n') { int k = (int)c[i + 1] ^ 32; result[j++] = (char)k; result[j++] = '.'; }

Page 31: Oops pramming with examples

} Console.Write("The Abbreviation for {0} is ", str); Console.WriteLine(result); Console.ReadLine(); } } class FileRead {

public void readdata() { FileStream fs = new FileStream(@"E:\Docs\test.txt", FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs);//Position the File Pointer at the Beginning of the File sr.BaseStream.Seek(0, SeekOrigin.Begin);//Read till the End of the File is Encountered string str = sr.ReadLine(); while (str != null) { Console.WriteLine("{0}", str); str = sr.ReadLine(); } //Close the Writer and File sr.Close(); fs.Close(); } } public void WorkThreadFunction() { for (int i = 0; i < 5; i++) { Console.WriteLine("Simple Thread"); } } public class MyGenericArray<T> { private T[] array; public MyGenericArray(int size) { array = new T[size + 1]; }

public T getItem(int index) { return array[index]; }

Page 32: Oops pramming with examples

public void setItem(int index, T value) { array[index] = value; } } } public class Base { public virtual void print() { Console.Write("df"); } public void display() { Console.Write("df2"); } }

public class Derived:Base { public new void display() { Console.Write("df3"); }

public override void print() { Console.Write("df1"); } }

public static class MyExtensions { public static int WordCount(this String str) { return str.Split(new char[] { ' ', '.', ',' }).Length; } } }