SlideShare a Scribd company logo
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";
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);
//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, @"bSS*");
str = "make maze and manage to measure it";
Console.WriteLine("Matching words start with 'm' and ends with 'e':");
showMatch(str, @"bmS*eb");
//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;
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
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++;
}
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;
}
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);
//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
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();
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();
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();
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)
{
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;
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
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");
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
{
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++;
}
}
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:Docstest.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)
{
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;
}
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)
{
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);
}
}
//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;
}
}
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
{
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; }
}
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);
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());
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
{
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; }
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="Tom@abc.com", Phone="9328298765"},
new ContactInfo {ID=112, Email="Jerry123@aaa.com", Phone="9876543201"},
new ContactInfo {ID=113, Email="Bobstar@aaa.com", Phone="9087467653"},
new ContactInfo {ID=114, Email="Markantony@qqq.com", 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);
}
}
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++] = '.';
}
}
Console.Write("The Abbreviation for {0} is ", str);
Console.WriteLine(result);
Console.ReadLine();
}
}
class FileRead
{
public void readdata()
{
FileStream fs = new FileStream(@"E:Docstest.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];
}
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;
}
}
}

More Related Content

What's hot

Sdl Basic
Sdl BasicSdl Basic
Sdl Basic
roberto viola
 
06 Loops
06 Loops06 Loops
06 Loops
maznabili
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
Mohammad Shaker
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
Cory Forsyth
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
Seok-joon Yun
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
Ramesh Nair
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
Seok-joon Yun
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
Sergey Platonov
 
Why rust?
Why rust?Why rust?
Why rust?
Mats Kindahl
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
tcurdt
 
Go a crash course
Go   a crash courseGo   a crash course
Go a crash course
Eleanor McHugh
 
Shell programming 2
Shell programming 2Shell programming 2
Shell programming 2
Kalkey
 
Shell programming 2
Shell programming 2Shell programming 2
Shell programming 2
Gourav Varma
 
Clojure 1.1 And Beyond
Clojure 1.1 And BeyondClojure 1.1 And Beyond
Clojure 1.1 And Beyond
Mike Fogus
 
Swift 2
Swift 2Swift 2
Swift 2
Jens Ravens
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
Eleanor McHugh
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
ESUG
 
C++ L07-Struct
C++ L07-StructC++ L07-Struct
C++ L07-Struct
Mohammad Shaker
 

What's hot (20)

Sdl Basic
Sdl BasicSdl Basic
Sdl Basic
 
06 Loops
06 Loops06 Loops
06 Loops
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
Why rust?
Why rust?Why rust?
Why rust?
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
Go a crash course
Go   a crash courseGo   a crash course
Go a crash course
 
Shell programming 2
Shell programming 2Shell programming 2
Shell programming 2
 
Shell programming 2
Shell programming 2Shell programming 2
Shell programming 2
 
Clojure 1.1 And Beyond
Clojure 1.1 And BeyondClojure 1.1 And Beyond
Clojure 1.1 And Beyond
 
Swift 2
Swift 2Swift 2
Swift 2
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
C++ L07-Struct
C++ L07-StructC++ L07-Struct
C++ L07-Struct
 

Viewers also liked

Paper id 29201412
Paper id 29201412Paper id 29201412
Paper id 29201412
IJRAT
 
Paper id 28201413
Paper id 28201413Paper id 28201413
Paper id 28201413
IJRAT
 
Paper id 24201492
Paper id 24201492Paper id 24201492
Paper id 24201492IJRAT
 
Paper id 2520141231
Paper id 2520141231Paper id 2520141231
Paper id 2520141231
IJRAT
 
Instituto tecnologico de cerro azul
Instituto tecnologico de cerro azulInstituto tecnologico de cerro azul
Instituto tecnologico de cerro azul
Ediel Domingo Santos
 
Paper id 2120143
Paper id 2120143Paper id 2120143
Paper id 2120143IJRAT
 
Paper id 25201466
Paper id 25201466Paper id 25201466
Paper id 25201466IJRAT
 
2d work slide show
2d work slide show2d work slide show
2d work slide show
Libby Lynch
 
Paper id 21201410
Paper id 21201410Paper id 21201410
Paper id 21201410IJRAT
 
Paper id 25201478
Paper id 25201478Paper id 25201478
Paper id 25201478IJRAT
 
Paper id 21201470
Paper id 21201470Paper id 21201470
Paper id 21201470IJRAT
 
Paper id 25201475
Paper id 25201475Paper id 25201475
Paper id 25201475IJRAT
 
Paper id 27201430
Paper id 27201430Paper id 27201430
Paper id 27201430
IJRAT
 
Paper id 28201451
Paper id 28201451Paper id 28201451
Paper id 28201451
IJRAT
 
The Ukraine and Me
The Ukraine and MeThe Ukraine and Me
The Ukraine and Me
huckrachael
 
Paper id 26201483
Paper id 26201483Paper id 26201483
Paper id 26201483
IJRAT
 
Paper id 25201482
Paper id 25201482Paper id 25201482
Paper id 25201482IJRAT
 
Paper id 252014121
Paper id 252014121Paper id 252014121
Paper id 252014121IJRAT
 
Paper id 252014144
Paper id 252014144Paper id 252014144
Paper id 252014144IJRAT
 
Paper id 212014107
Paper id 212014107Paper id 212014107
Paper id 212014107IJRAT
 

Viewers also liked (20)

Paper id 29201412
Paper id 29201412Paper id 29201412
Paper id 29201412
 
Paper id 28201413
Paper id 28201413Paper id 28201413
Paper id 28201413
 
Paper id 24201492
Paper id 24201492Paper id 24201492
Paper id 24201492
 
Paper id 2520141231
Paper id 2520141231Paper id 2520141231
Paper id 2520141231
 
Instituto tecnologico de cerro azul
Instituto tecnologico de cerro azulInstituto tecnologico de cerro azul
Instituto tecnologico de cerro azul
 
Paper id 2120143
Paper id 2120143Paper id 2120143
Paper id 2120143
 
Paper id 25201466
Paper id 25201466Paper id 25201466
Paper id 25201466
 
2d work slide show
2d work slide show2d work slide show
2d work slide show
 
Paper id 21201410
Paper id 21201410Paper id 21201410
Paper id 21201410
 
Paper id 25201478
Paper id 25201478Paper id 25201478
Paper id 25201478
 
Paper id 21201470
Paper id 21201470Paper id 21201470
Paper id 21201470
 
Paper id 25201475
Paper id 25201475Paper id 25201475
Paper id 25201475
 
Paper id 27201430
Paper id 27201430Paper id 27201430
Paper id 27201430
 
Paper id 28201451
Paper id 28201451Paper id 28201451
Paper id 28201451
 
The Ukraine and Me
The Ukraine and MeThe Ukraine and Me
The Ukraine and Me
 
Paper id 26201483
Paper id 26201483Paper id 26201483
Paper id 26201483
 
Paper id 25201482
Paper id 25201482Paper id 25201482
Paper id 25201482
 
Paper id 252014121
Paper id 252014121Paper id 252014121
Paper id 252014121
 
Paper id 252014144
Paper id 252014144Paper id 252014144
Paper id 252014144
 
Paper id 212014107
Paper id 212014107Paper id 212014107
Paper id 212014107
 

Similar to Oops pramming with examples

C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)jahanullah
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
GrejoJoby1
 
Loops
LoopsLoops
Loops
Kamran
 
Loops (1)
Loops (1)Loops (1)
Loops (1)
esmail said
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
Folio3 Software
 
Oop object oriented programing topics
Oop object oriented programing topicsOop object oriented programing topics
Oop object oriented programing topics
(•̮̮̃•̃) Prince Do Not Work
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
Chhom Karath
 
06.Loops
06.Loops06.Loops
06.Loops
Intro C# Book
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
caswenson
 
Templates
TemplatesTemplates
Templates
Farwa Ansari
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
Rohit Rao
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
Troy Miles
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
Niket Chandrawanshi
 
srgoc
srgocsrgoc

Similar to Oops pramming with examples (20)

C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
Loops
LoopsLoops
Loops
 
Loops (1)
Loops (1)Loops (1)
Loops (1)
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
 
Oop object oriented programing topics
Oop object oriented programing topicsOop object oriented programing topics
Oop object oriented programing topics
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
06.Loops
06.Loops06.Loops
06.Loops
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
PSI 3 Integration
PSI 3 IntegrationPSI 3 Integration
PSI 3 Integration
 
Templates
TemplatesTemplates
Templates
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
srgoc
srgocsrgoc
srgoc
 

Recently uploaded

Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 

Recently uploaded (20)

Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 

Oops pramming with examples

  • 1. 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";
  • 2. 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);
  • 3. //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, @"bSS*"); str = "make maze and manage to measure it"; Console.WriteLine("Matching words start with 'm' and ends with 'e':"); showMatch(str, @"bmS*eb"); //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;
  • 4. 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
  • 5. 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++;
  • 6. } 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; }
  • 7. 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);
  • 8. //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
  • 9. 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();
  • 10. 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();
  • 11. 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();
  • 12. 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) {
  • 13. 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;
  • 14. 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
  • 15. 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");
  • 16. 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
  • 17. { 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++; }
  • 18. } 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:Docstest.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)
  • 19. { 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; }
  • 20. 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) {
  • 21. 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);
  • 22. } } //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; } }
  • 23. 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 {
  • 24. 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; } }
  • 25. 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);
  • 26. 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());
  • 27. 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 {
  • 28. 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; }
  • 29. 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="Tom@abc.com", Phone="9328298765"}, new ContactInfo {ID=112, Email="Jerry123@aaa.com", Phone="9876543201"}, new ContactInfo {ID=113, Email="Bobstar@aaa.com", Phone="9087467653"}, new ContactInfo {ID=114, Email="Markantony@qqq.com", 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);
  • 30. } } 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++] = '.'; }
  • 31. } Console.Write("The Abbreviation for {0} is ", str); Console.WriteLine(result); Console.ReadLine(); } } class FileRead { public void readdata() { FileStream fs = new FileStream(@"E:Docstest.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]; }
  • 32. 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; } } }