I have create slides which lists examples of oops programming concepts including looping,enums,structures,linq,threading,delegates,generics,inheritenc..so on.
Rust
Why do you care about Rust? Who has the time to learn all these new languages? It seems like a new one is popping up every other week and this trend is growing at an exponential rate. Good news, a fair number of them are crafted really well and efficiently solve specific problems. Bad news, how do you keep up with all of this, let alone decide which languages to include in your companies technology portfolio.
Despite the challenges of all these new languages, a majority of developers are intrigued about the idea of becoming a polyglot, but don't know where to begin or don't have the time. In my polyglot travels, there is one language of late that is the sure-fire answer to the above questions, Rust.
In this talk I’ll explore the value behind becoming more polyglotic as a developer, how to pick languages to learn, and then dive deep in the the language of Rust. Which in my opinion, is hands down the best up and coming languages to learn.
About the Presenter
Anthony Broad-Crawford has been a developer since the year 2000 with a short side stint as a semi-professional poker player. Since his transition to software development Anthony has...
1. Built 8 patent receiving technologies
2. Founded two global companies
3. Been a CTO (3x), CPO (1x), and CEO (1x)
and is currently the CTO at Fooda where he manages product, user experience, and engineering. Fooda is predominantly web and mobile technology company focused on bringing great & healthy food from the best restaurant's to people while at the office.
Through his career, in production applications Anthony has used Ruby, Java, Jave (Android), Objective-C and Swift, .NET, Erlang, Scala, Node.JS, LISP, Smalltalk, and even assembly, with his recent favorite, Rust . No, not all at the same time in the same application.
Anthony now spends his time building great teams, that leverage great technology, to build great products, but still looks to codes every chance he can get :)
Asterisk: PVS-Studio Takes Up TelephonyAndrey Karpov
Asterisk is a software implementation of a telephone private branch exchange (PBX); it was created in 1999 by Mark Spencer of Digium. Like any PBX, it allows attached telephones to make calls to one another, and to connect to other telephone services, such as the public switched telephone network (PSTN) and Voice over Internet Protocol (VoIP) services. Its name comes from the asterisk symbol, *.
Asterisk is released under a dual license model, using the GNU General Public License (GPL) as a free software license and a proprietary software license to permit licensees to distribute proprietary, unpublished system components.
In this article, we are going to discuss the results of the check of the Asterisk project by PVS-Studio 5.18.
The project seems to be regularly checked by the Coverity analyzer, which is indicated by comments like this one:
/* Ignore check_return warning from Coverity for ast_exists_extension below */
However, I still found some disappointing typos in the code. Let's try to figure them out as well as other potential issues. The source code was downloaded from the project's SVN repository.
Rust
Why do you care about Rust? Who has the time to learn all these new languages? It seems like a new one is popping up every other week and this trend is growing at an exponential rate. Good news, a fair number of them are crafted really well and efficiently solve specific problems. Bad news, how do you keep up with all of this, let alone decide which languages to include in your companies technology portfolio.
Despite the challenges of all these new languages, a majority of developers are intrigued about the idea of becoming a polyglot, but don't know where to begin or don't have the time. In my polyglot travels, there is one language of late that is the sure-fire answer to the above questions, Rust.
In this talk I’ll explore the value behind becoming more polyglotic as a developer, how to pick languages to learn, and then dive deep in the the language of Rust. Which in my opinion, is hands down the best up and coming languages to learn.
About the Presenter
Anthony Broad-Crawford has been a developer since the year 2000 with a short side stint as a semi-professional poker player. Since his transition to software development Anthony has...
1. Built 8 patent receiving technologies
2. Founded two global companies
3. Been a CTO (3x), CPO (1x), and CEO (1x)
and is currently the CTO at Fooda where he manages product, user experience, and engineering. Fooda is predominantly web and mobile technology company focused on bringing great & healthy food from the best restaurant's to people while at the office.
Through his career, in production applications Anthony has used Ruby, Java, Jave (Android), Objective-C and Swift, .NET, Erlang, Scala, Node.JS, LISP, Smalltalk, and even assembly, with his recent favorite, Rust . No, not all at the same time in the same application.
Anthony now spends his time building great teams, that leverage great technology, to build great products, but still looks to codes every chance he can get :)
Asterisk: PVS-Studio Takes Up TelephonyAndrey Karpov
Asterisk is a software implementation of a telephone private branch exchange (PBX); it was created in 1999 by Mark Spencer of Digium. Like any PBX, it allows attached telephones to make calls to one another, and to connect to other telephone services, such as the public switched telephone network (PSTN) and Voice over Internet Protocol (VoIP) services. Its name comes from the asterisk symbol, *.
Asterisk is released under a dual license model, using the GNU General Public License (GPL) as a free software license and a proprietary software license to permit licensees to distribute proprietary, unpublished system components.
In this article, we are going to discuss the results of the check of the Asterisk project by PVS-Studio 5.18.
The project seems to be regularly checked by the Coverity analyzer, which is indicated by comments like this one:
/* Ignore check_return warning from Coverity for ast_exists_extension below */
However, I still found some disappointing typos in the code. Let's try to figure them out as well as other potential issues. The source code was downloaded from the project's SVN repository.
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
An overview of some of the history of JavaScript, how it became ECMAScript (and what Ecma is), as well as highlights of the new features and syntax in ES6 aka ES2015.
Originally presented to the New York Public Library on June 4 2015.
A brief look at the new features coming in Javascript ES6:
- Scope and control
- Iterators and Generators
- Collections
- Typed objects
- Direct proxies
- Template strings
- API improvements
- Modularity
Не так давно Гор Нишанов представил свой доклад: C++ Coroutines a negative overhead abstraction. В этом докладе Гор упомянул, что предложенный дизайн корутин позволяет их использовать практически в любых окружениях, в том числе и с "бедным" C++ рантаймом.
Я решил попробовать запустить корутины в следующих окружениях: обычное приложение, драйвер ОС Windows, EFI приложение. Только в одном из этих окружений есть полноценный C++ рантайм и поддержка исключений, в остальных ничего этого нет. Более того, EFI приложение вообще выполняется до старта ОС.
Я хочу рассказать о том, как мне удалось запустить корутины в этих окружениях, поговорим о том, какие проблемы существуют в асинхронном системном программировании и как их можно обойти.
This presentation was held at the Stockholm Rust Meetup in September 2019.
This is a brief introduction to Rust and highlights some of the problems with C++ that it attempts to solve. It also contain a brief introduction to the ownership model and the borrow checker that Rust uses.
A reworking of my 2010 RubyConf lightning talk introducing Go via a concurrent implementation of MapReduce. This code is probably buggy as hell and the design awful but it's also a reasonably good intro to the full breadth of Go.
Implementing Software Machines in C and GoEleanor McHugh
The next iteration of the talk I gave at Progscon, this introduces examples of Map implementation (useful for caches etc.) and outlines for addition of processor core code in a later talk.
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
An overview of some of the history of JavaScript, how it became ECMAScript (and what Ecma is), as well as highlights of the new features and syntax in ES6 aka ES2015.
Originally presented to the New York Public Library on June 4 2015.
A brief look at the new features coming in Javascript ES6:
- Scope and control
- Iterators and Generators
- Collections
- Typed objects
- Direct proxies
- Template strings
- API improvements
- Modularity
Не так давно Гор Нишанов представил свой доклад: C++ Coroutines a negative overhead abstraction. В этом докладе Гор упомянул, что предложенный дизайн корутин позволяет их использовать практически в любых окружениях, в том числе и с "бедным" C++ рантаймом.
Я решил попробовать запустить корутины в следующих окружениях: обычное приложение, драйвер ОС Windows, EFI приложение. Только в одном из этих окружений есть полноценный C++ рантайм и поддержка исключений, в остальных ничего этого нет. Более того, EFI приложение вообще выполняется до старта ОС.
Я хочу рассказать о том, как мне удалось запустить корутины в этих окружениях, поговорим о том, какие проблемы существуют в асинхронном системном программировании и как их можно обойти.
This presentation was held at the Stockholm Rust Meetup in September 2019.
This is a brief introduction to Rust and highlights some of the problems with C++ that it attempts to solve. It also contain a brief introduction to the ownership model and the borrow checker that Rust uses.
A reworking of my 2010 RubyConf lightning talk introducing Go via a concurrent implementation of MapReduce. This code is probably buggy as hell and the design awful but it's also a reasonably good intro to the full breadth of Go.
Implementing Software Machines in C and GoEleanor McHugh
The next iteration of the talk I gave at Progscon, this introduces examples of Map implementation (useful for caches etc.) and outlines for addition of processor core code in a later talk.
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
The slides from the C++ and OOPS Crash Course conducted for ACM DBIT by Grejo Joby.
Learn the concepts of OOPS and C++ Programming in the shortest time with these notes.
The presentation helps us in understanding the different concepts associated with TypeScript. What is TypeScript? Why is TypeScript used and the different applications of TypeScript. For more information you can simply visit: http://mobile.folio3.com/
In this chapter we will examine the loop programming constructs through which we can execute a code snippet repeatedly. We will discuss how to implement conditional repetitions (while and do-while loops) and how to work with for-loops. We will give examples of different possibilities to define loops, how to construct them and some of their key usages. Finally, we will discuss the foreach-loop construct and how we can use multiple loops placed inside each other (nested loops).
Game Design and Development Workshop Day 1Troy Miles
This course teaches you how to build awesome video games using Cocos2Dx. Cocos2Dx is a feature packed, free game development engine. It is cross platform, high performance, and supports three languages: C++, Lua and JavaScript. With it, you can write games for iOS, Android, Windows, Mac, and the Web. It is nothing short of amazing and this course teaches you how to use it. We will program Cocos2Dx in JavaScript, but this is not a programming class. If you don't know how to write code in JavaScript or some other curly brace language, this is not the course for you. For those whose JavaScript is rusty, we will do quick language overview. Don't let the JavaScript part fool you. Cocos2Dx is built from highly optimized C++ and OpenGL, JavaScript is used for game logic, not graphics. Our games will run at a super fast, 60 frames a second.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
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;
}
}
}