Top Banner
1 | Page KnackHook Knowledge Holder [email protected] www.knackhook.com C#.Net
234

knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder [email protected] Table of Contents 1. About .Net

Jul 08, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

1 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

C#.Net

Page 2: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

2 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Table of Contents

1. About .Net? ......................................................................................................... 8

2. About .Net Framework ........................................................................................ 9

3. About Common Language Runtime (CLR) and its Services? ........................................................................................................... 13

4. What is managed code in .Net? ......................................................................... 14

5. What is unmanaged code in .Net? ..................................................................... 15

6. About Common Type System? ........................................................................... 15

7. About Common Language Specification? ........................................................... 15

8. About Framework Class Library?........................................................................ 16

9. About Visual Studio? ......................................................................................... 16

10. About Execution flow of C# Program? ................................................................ 20

11. About Hello World! Program? ........................................................................... 21

12. About static void Main(string[] args)? ................................................................ 22

13. About Write, WriteLine, Read, ReadLine and ReadKey methods? ............................................................................................ 22

14. About Data Types? ............................................................................................ 24

15. About difference between Decimal, Float and Double in .NET? ................................................................................................. 25

16. How to get Max and Min range of data types? .................................................. 26

17. About Data type conversion? ............................................................................ 27

18. About Boxing and Unboxing? ............................................................................ 28

19. About Operators? .............................................................................................. 30

20. About Ternary Operator? .................................................................................. 33

21. About is and as Operators? ................................................................................ 34

Page 3: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

3 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

22. About Null Coalescing Operator “??” ? .............................................................. 35

23. About Bitwise Operators? ................................................................................. 36

24. About difference between int.Parse,Convert.ToInt32 and int.TryParse? ...................................................... 38

25. Conditional Statements? ................................................................................... 40

26. About if? ........................................................................................................... 41

27. About if-else? .................................................................................................... 41

28. About switch vs if-else-if? .................................................................................. 42

29. About for vs foreach? ........................................................................................ 43

30. About while vs do-while? .................................................................................. 45

31. About polyndrome number? ............................................................................. 46

32. About Prime number? ....................................................................................... 47

33. About Methods? ............................................................................................... 48

34. About Instance method? ................................................................................... 49

35. About Static Method? ....................................................................................... 50

36. About value type parameters? .......................................................................... 51

37. About reference type parameter? ..................................................................... 52

38. About out parameter? ....................................................................................... 53

39. About parameter array? .................................................................................... 54

40. About Arrays? ................................................................................................... 55

41. About storing different data types values in to an array? ................................................................................................................ 56

42. About Obsolete Attribute in C#? ........................................................................ 57

43. About Tuple in C#? ............................................................................................ 58

44. About Finalize and Dispose Methods? ............................................................... 59

45. About using keyword? ....................................................................................... 61

46. About Use of New Keyword? ............................................................................. 62

Page 4: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

4 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

47. About sorting an array elements? ...................................................................... 64

48. About sorting elements with Bubble sort? ......................................................... 64

49. About structures? .............................................................................................. 66

50. About enum data type? ..................................................................................... 68

51. About reversing a string? ................................................................................... 69

52. About string vs stringbuilder? ............................................................................ 70

53. About Difference b/w .ToString() and Convert.ToString()? ........................................................................................... 71

54. About Recursive Method? ................................................................................. 73

55. About Collections? ............................................................................................ 74

56. About ArrayList? ................................................................................................ 74

57. About Hashtable? .............................................................................................. 75

58. About Stack? ..................................................................................................... 76

59. About Difference b/w Pop() and Peek()? ........................................................... 77

60. About Queue? ................................................................................................... 79

61. About difference b/w DeQueue() and Peek()? ................................................... 80

62. About Generic Collection Dictionary? ................................................................ 82

63. About Generic Collection List? ........................................................................... 84

64. About Generic Collection Queue? ...................................................................... 85

65. About Generic Collection Stack? ........................................................................ 87

66. About SortedList? .............................................................................................. 88

67. About IEnumerable? .......................................................................................... 89

68. About IQueryable? ............................................................................................ 91

69. What's the difference between IEnumerable<T> and List<T> ? ..................................................................................................... 93

70. About Class? ...................................................................................................... 93

71. About public access modifier? ........................................................................... 94

Page 5: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

5 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

72. About private Access Modifier? ......................................................................... 96

73. About protected Access Modifier? ..................................................................... 97

74. About properties? ............................................................................................. 99

75. About default constructor?.............................................................................. 102

76. About parameter Constructor? ........................................................................ 103

77. About static constructor? ................................................................................ 104

78. About copy constructor? ................................................................................. 106

79. About private constructor? .............................................................................. 107

80. About static class? ........................................................................................... 108

81. About abstract class? ....................................................................................... 110

82. About interface?.............................................................................................. 111

83. About partial class? ......................................................................................... 114

84. About Data Abstraction and Encapsulation? .................................................... 116

85. About Method Overloading? ........................................................................... 121

86. About Operator Overloading? ......................................................................... 122

87. About Method Overriding? .............................................................................. 124

88. About Inheritance? .......................................................................................... 125

89. About single inheritance? ................................................................................ 128

90. About multi-level inheritance? ........................................................................ 129

91. About multiple inheritance? ............................................................................ 131

92. About multiple inheritance through interfaces? .............................................. 133

93. About multiple interface with one class and one interface? ........................................................................................................ 134

94. About Extension Method? ............................................................................... 135

95. About indexers? .............................................................................................. 136

96. About Generic Methods? ................................................................................. 137

Page 6: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

6 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

97. About Generic Classes?.................................................................................... 140

98. About Exception Handling?.............................................................................. 142

99. About dynamic, object and var keywords? ...................................................... 144

100. About LINQ with selection? ............................................................................. 147

101. LINQ with where condition? ............................................................................ 148

102. LINQ with select many? ................................................................................... 149

103. LINQ with Take? .............................................................................................. 150

104. LINQ with TakeWhile? ..................................................................................... 151

105. LINQ with Skip? ............................................................................................... 152

106. LINQ with Order by? ........................................................................................ 154

107. LINQ with Group By? ....................................................................................... 155

108. LINQ with Distinct? .......................................................................................... 157

109. LINQ with Union? ............................................................................................ 158

110. LINQ with intersect? ........................................................................................ 159

111. LINQ with Except? ........................................................................................... 160

112. LINQ with First? ............................................................................................... 161

113. LINQ with FirstOrDefault? ............................................................................... 162

114. LINQ with All? ................................................................................................. 163

115. LINQ with Count? ............................................................................................ 164

116. LINQ with Sum? ............................................................................................... 165

117. LINQ with Min, Max and Average? .................................................................. 165

118. LINQ with Join? ............................................................................................... 167

119. About Delegate? .............................................................................................. 168

120. About Multicast Delegate or chaining delegates? ............................................ 169

121. About Asynchronous Method call with Delegates? .......................................... 171

Page 7: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

7 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

122. About Asynchronous Method call with return value? ............................................................................................................. 172

123. About Anonymous method call? ...................................................................... 176

124. About Reflection? ............................................................................................ 177

125. About Basics of Threading?.............................................................................. 180

126. About Background thread? .............................................................................. 184

127. About Thread lifecycle? ................................................................................... 186

128. About difference b/w Abstarct class and Interface? ......................................... 189

129. About where to use interface? ........................................................................ 195

130. Can an interface inherit from another interface? ............................................. 205

131. Is it possible to create partial structs, interfaces and methods? ................................................................................................. 206

132. How do you create partial methods? ............................................................... 208

133. Why is it not a good idea to use Empty destructors? .................................................................................................... 209

134. We cannot create instances of static classes. Can we have constructors for static classes? .......................................................... 209

135. Can you prevent a class from being instantiated? ............................................ 210

136. Can a child class call the constructor of a base class?............................................................................................................... 211

137. If a child class instance is created, which class constructor is called first - base class or child class? ......................................... 212

138. Can you mark static constructor with access modifiers? ....................................................................................................... 213

139. Can you have parameters for static constructors? ........................................... 214

140. What happens if a static constructor throws an exception? ....................................................................................................... 216

141. If a method's return type is void, can you use a return keyword in the method? ....................................................................... 216

Page 8: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

8 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

142. About Dependency Injection? .......................................................................... 217

143. About implementation of DI through the Constructor?.................................................................................................... 219

144. About implementation of DI through the Property? ........................................ 220

145. About implementation of DI through the Method?.......................................... 222

146. About implementation of DI through the interface? ........................................ 223

147. About Singleton Design pattern? ..................................................................... 225

148. About Factory Method design pattern? ........................................................... 226

149. What are the Methods we can able to access with a,b,c objects in the following program? ........................................................... 231

150. In the following code finally block execute or not? .......................................... 232

151. How to implement only specified Methods in an interface? ........................................................................................................ 233

About .Net? .Net is a software development platform developed by Microsoft.

Using Dot Net we can build multiple applications like

• Console Application: A console application is an application that takes input and displays output

at a command line console with access to three basic data streams: standard input, standard

output and standard error. Ex : CMD Prompt

• Web Applications: A Web Application is an application which is having GUI and accessible

through the internet in web browser (IE, Crome, Firefox and Safari).A Web Application is a

collection of web pages. Ex : www.msn.com

• Windows Applications (Desktop Applications): An application that target to run in Windows OS

is called Windows Application or Desktop Application. Windows Application doesn’t need Web

Browser to run. Ex : Skype

• Windows Services: A service which runs on Windows environment is called a Windows Service:

Ex: Birthday Alarm of windows system.

Page 9: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

9 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

• Web Services: Web Service is distribution service where we can host web service and able to

consume it in different applications using internet. Ex : Paypal webservice

• Mobile Applications: An Application which targets to run on Mobile is called Mobile Application.

Ex : Whats App

• WPF Applications (Windows Presentation Foundation): WPF application is an Windows

Application which have good look and fell(GUI)

• Silverlight Applications: Silverlight application is a web application with good look and feel.

Dot Net Components:

• Dot Net Framework

• ASP.NET

• Visual Studio

About .Net Framework The .NET Framework is an integral Windows component that supports building and running the next generation of applications. It consists of 2 components.

• Common Language Runtime • Framework Class Library

.Net Framework Versions .Net Framework 1.0 in 2002 .Net Framework 1.1 in 2003 .Net Framework 2.0 in 2005 .Net Framework 3.0 in 2006 .Net Framework 3.5 in 2007 .Net Framework 4.0 in 2010 .Net Framework 4.5 in 2012 .Net Framework 4.5.1 in 2013 .Net Framework 1.1 Features:

1. Introduced ASP.NET Mobile Controls 2. The .NET Framework Data Provider for ODBC, which previously was available as a Web

download only, now ships with the .NET Framework under the namespace System.Data.Odbc 3. The .NET Framework version 1.1 supports side-by-side execution. Side-by-side execution is the

ability to store and execute multiple versions of an application or component on the same computer.

Page 10: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

10 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

If you have some application requiring assembly version 1.2.0.0 to run properly and some of your application requires same file but having version 1.3.0.0 then you can have both assemblies on your computer and at the same time, you can have both running, using different assemblies at runtime :-) Ajax Tool Kit .Net Framework 2.0 Features:

1. The new generation of 64-bit computers enables the creation of applications that can run faster and take advantage of more memory than is available to 32-bit applications

2. The Microsoft .NET Framework 2.0 includes significant enhancements to all areas of ASP.NET, Master pages allow you to create a consistent layout for all the pages in a site, and themes allow you to define a consistent look for controls and static text. To help protect your sites, you can precompile a Web site to produce executable code from source files (both code files and the markup in .aspx pages). You can then deploy the resulting output, which does not include any source information, to a production server.

3. Applications can now access File Transfer Protocol resources using the WebRequest, WebResponse, and WebClient classes.

4. Four Microsoft programming languages explicitly target the .NET Framework: Visual C#, Microsoft C/C++, Visual J#, and Visual Basic.

5. Using the classes in the System.Net.Mail and System.Net.Mime namespaces, applications can send e-mail to one or more recipients. Mail can be sent with alternate views and can include attachments. Sending carbon copies and blind carbon copies is also supported.

6. ClickOnce deployment allows you to deploy self-updating Windows applications that can be installed and run as easily as Web applications. You can deploy Windows client and command-line applications.

.Net Framework 3.0 Features: The .NET Framework version 3.0 was issued solely to include the following technologies in the .NET Framework and in the Windows Software Development Kit (SDK):

• Windows Communication Foundation: Windows Communication Foundation (WCF) is a runtime and a set of APIs for creating systems that send messages between services and clients. The same infrastructure and APIs are used to create applications that communicate with other applications on the same computer system or on a system that resides in another company and is accessed over the Internet. WCF has all features of following distributed technologies: Web Service, Microsoft Message Queuing (MSMQ), Remoting

• Windows Presentation Foundation: Windows Presentation Foundation (WPF) provides developers with a unified programming model for building rich Windows smart client user experiences that incorporate UI, media, and documents.

• Windows Workflow Foundation: Windows Workflow Foundation, a core component of .NET Framework 3.0, provides a programming model, run-time engine, and tools for building workflow applications. A workflow is a discrete series of activities that model the steps involved in a business process.A workflow is created and maintained by the workflow run-time engine. There can be several workflow engines within an application domain, and each workflow engine can support multiple workflows running concurrently. The run-time enables idle workflows to be unloaded from memory, persisted to a store, and reloaded whenever input is received.

Page 11: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

11 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

• Windows CardSpace: The Internet continues to be increasingly valuable, and yet also faces significant challenges. Online identity theft, fraud, and privacy concerns are rising. Users must track a growing number of accounts and passwords. This burden results in "password fatigue," and that results in insecure practices, such as reusing the same account names and passwords at many sites. CardSpace is Microsoft's implementation of an Identity Metasystem that enables users to choose from a portfolio of identities that belong to them and use them in contexts where they are accepted, independent of the underlying identity systems where the identities originate and are used. This topic explains the issue and the CardSpace solution in greater detail, and outlines how Windows Communication Foundation (WCF) users can use CardSpace. Many of these issues are rooted in the lack of a widely adopted identity solution for the Internet. Password security mechanism to authenticate and authorize user access. Windows Cardspace has been replaced with Microsoft Passport authentication.

.Net Framework 3.5 Features:

• Language-Integrated Query (LINQ) is a new feature in Visual Studio 2008 and the .NET Framework 3.5. LINQ extends powerful query capabilities to the language syntax of C# and Visual Basic in the form of standard, easily-learned query patterns.

• The most significant advance is improved support for the development of AJAX-enabled Web sites.

• The .NET Framework 3.5 unifies the Windows Workflow Foundation (WF) and Windows Communication Foundation (WCF) frameworks so that you can use WF as a way to author WCF services or expose your existing WF workflow as a service. This enables you to create services that can be persisted, can easily transfer data in and out of a workflow, and can enforce application-level protocols.

.Net Framework 3.5 SP1 Features: The .NET Framework Client Profile is a subset of the full .NET Framework that targets client applications. This improves the installation experience on computers that do not already have the .NET Framework installed. .Net Framework 4.0 Features:

• The .NET Framework 4 Client Profile supports more platforms than in previous versions and provides a fast deployment experience for your applications.

• The .NET Framework 4 provides background garbage collection. This feature replaces concurrent garbage collection in previous versions and provides better performance.

• The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework.

• The Managed Extensibility Framework (MEF) is a new library in the .NET Framework 4 that helps you build extensible and composable applications.

• The .NET Framework 4 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The

Page 12: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

12 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

new System.Threading.Tasks namespace and other related types support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax.

• Web Forms controls, including a new Chart control. • MVC, including new helper methods for views, support for partitioned MVC applications, and

asynchronous controllers. • ADO.NET provides new features for the Entity Framework, including persistence-ignorant

objects, functions in LINQ queries, and customized object layer code generation. .Net Framework 4.5 Features:

• Windows Store apps are designed for specific form factors and leverage the power of the Windows operating system. A subset of the .NET Framework 4.5 is available for building Windows Store apps for Windows by using C# or Visual Basic.

• The Portable Class Library project in Visual Studio 2012 enables you to write and build managed assemblies that work on multiple .NET Framework platforms. Using a Portable Class Library project, you choose the platforms (such as Windows Phone and .NET for Windows Store apps) to target. The available types and members in your project are automatically restricted to the common types and members across these platforms.

• Support for new HTML5 form types. .Net Framework 4.5.1 Features: Debugging Feature Improvements 64-Bit Edit and Continue support in Visual Studio 2013 : in debug mode we can edit and continue the changes. Inspecting Method return value while debugging using Autos Window as well as a pseudo variable $ReturnValue : we can check the result of return value easily. ADO.NET Connection Resiliency :ADO.NET connection recovery has been increased. Application Performance Improvements ASP.NET Application Suspension :We have ablility to suspend the web application when there is no request for that application. On-Demand Large-Object heap compaction :The On-demand large object heap compaction is now supported in .NET framework 4.5.1 to avoid the OutOfMemory exception. Multi-core JIT Improvements : It enhance the launch time of the application 40-50 %

Page 13: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

13 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Common Language Runtime (CLR) and its Services?

The common language runtime is the foundation of the .NET Framework. It is responsible for managing

code execution at run time, and provides core services such as compilation, memory management,

thread management, code execution, enforcement of type safety, and code safety verification.

Compilers target the common language runtime, which defines the basic data types available to

application developers. Because it provides a managed environment for code execution, the common

language runtime enhances developer productivity and contributes to the development of robust

applications.

Page 14: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

14 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

• Class loader, which loads classes into CLR.

• MSIL to native code compiles, this converts MSIL code into native code.

• Code manager, this manages the code during execution.

• Memory allocation and Garbage collector, this performs automatic memory management.

• Security engine, this enforces security restrictions as code level security folder level and

machine level security using tools provided by Microsoft .NET and using .NET Framework setting

under control panel.

• Type checker, which enforces strict type checking.(CTS and CLS)

• Thread support, which provides multithreading support to applications.

• Exception manager, which provides a mechanism to handle the run-time exceptions handling.

• Debug engine, which allows developer to debug different types of applications.

• COM marshaler, which allows .NET applications to exchange data with COM applications.

• Base class library support, which provides the classes (types) that the applications need at run

time.

What is managed code in .Net?

The code that runs under the guidance of common language runtime (CLR) is called managed code. The

versioning and registration problem which are formally handled by the windows programming are

solved in .Net with the introduction of managed code. The managed code contains all the versioning and

type information that the CLR use to run the application.

Ex: The code developed by .Net supporting languages like C#.Net, VB.Net, F#.Net etc.

Page 15: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

15 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

What is unmanaged code in .Net?

The code, which is developed outside .NET, Framework is known as unmanaged code.

Applications that do not run under the control of the CLR are said to be unmanaged, and certain

languages such as C++ can be used to write such applications, which, for example, access low - level

functions of the operating system. Background compatibility with code of VB, ASP and COM are

examples of unmanaged code.

Unmanaged code can be unmanaged source code and unmanaged compile code.

Unmanaged code is executed with help of wrapper classes.

Wrapper classes are of two types: CCW (COM Callable Wrapper) and RCW (Runtime Callable Wrapper).

Wrapper is used to cover difference with the help of CCW and RCW.

About Common Type System?

The common type system defines how types are declared, used, and managed in the runtime, and is

also an important part of the runtime's support for cross-language integration. The common type

system performs the following functions:

Establishes a framework that helps enable cross-language integration, type safety, and high

performance code execution.

Provides an object-oriented model that supports the complete implementation of many programming

languages.

Defines rules that languages must follow, which helps ensure that objects written in different languages

can interact with each other.

About Common Language Specification?

CLS is a set of specifications that all languages and libraries need to follow

This will ensure interoperability between languages

The CLS rules define a subset of the common type system; that is, all the rules that apply to the common

type system apply to the CLS, except where stricter rules are defined in the CLS. The CLS helps enhance

and ensure language interoperability by defining a set of features that developers can rely on to be

available in a wide variety of languages. The CLS also establishes requirements for CLS compliance; these

help you determine whether your managed code conforms to the CLS and to what extent a given tool

supports the development of managed code that uses CLS features.

If your component uses only CLS features in the API that it exposes to other code (including derived

classes), the component is guaranteed to be accessible from any programming language that supports

the CLS. Components that adhere to the CLS rules and use only the features included in the CLS are said

to be CLS-compliant components.

Most of the members defined by types in the .NET Framework class library are CLS-compliant. However,

some types in the class library have one or more members that are not CLS-compliant. These members

Page 16: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

16 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

enable support for language features that are not in the CLS. (Keywords, Interface methods, Accessor

metadata, Event method metadata, FlagsAttribute and Value encodings).

About Framework Class Library?

The .NET Framework class library is a collection of reusable types that tightly integrate with the common

language runtime. The class library is object oriented, providing types from which your own managed

code can derive functionality. This not only makes the .NET Framework types easy to use, but also

reduces the time associated with learning new features of the .NET Framework. In addition, third-party

components can integrate seamlessly with classes in the .NET Framework.

For example, the .NET Framework collection classes implement a set of interfaces that you can use to

develop your own collection classes. Your collection classes will blend seamlessly with the classes in the

.NET Framework.

About Visual Studio?

Visual Studio .NET is a complete set of development tools for building ASP Web applications, XML Web

services, desktop applications, and mobile applications. Visual Basic .NET, Visual C++ .NET, Visual

C# .NET, and Visual J# .NET all use the same integrated development environment (IDE), which allows

them to share tools and facilitates in the creation of mixed-language solutions. In addition, these

languages leverage the functionality of the .NET Framework, which provides access to key technologies

that simplify the development of ASP Web applications and XML Web services.

Visual Studio includes:

A code editor supporting

Page 17: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

17 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

IntelliSense

Code snippets and

Code refactoring.

The integrated debugger works both

As a source-level debugger and

As a machine-level debugger.

Forms designer for building GUI applications,

Class designer,

And other SW tools

Visual Studio 2005:

Development Environment

Code Editing

Projects, Solutions, and Items

Building, Testing, and Deployment

Visual Studio 2008:

DataRepeater Control

Line and Shape Controls

.NET Framework Client Profile Support

ClickOnce Deployment

Language-Integrated Query (LINQ) is a new set of features in Visual Studio 2008 that extend powerful

query capabilities into the language syntax of C# and Visual Basic.

Visual Studio 2010:

Auto-Implemented Properties

Collection Initializers

Implicit Line Continuation

Multiline Lambda Expressions and Subroutines

New Command-Line Option for Specifying a Language Version

Page 18: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

18 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Type Equivalence Support

Dynamic Support

Covariance and Contravariance

Navigate To

Highlighting References

Generate From Usage

IntelliSense Suggestion Mode

Visual Studio 2012:

Designing and building Windows Store apps

Debugging, optimizing, and publishing Windows Store apps

Designing and building Windows Phone apps

Testing, optimizing, and publishing Windows Phone apps

Developing applications and collaborating more effectively as a team

ASP.NET 4.5 Core Services

ASP.NET 4.5 Web Forms

Visual Studio 2013:

Open the Resolve menu when typing it happens once in a while that you haven’t included the

namespace you need at the top of your file. One common example is Trace found in System.Diagnostics.

If you write Trace, Visual Studio suggests TraceMode and other things, but no Trace. To quickly solve

this, type Trace followed by CTRL + SPACE +. And the Resolve menu comes up where you can select to

include using System.Diagnostics; to make Trace available. Very handy.

64 bit Edit and Continue Have we been waiting for this one or what?!? Finally, by using .Net Framework

4.5.1, we can have the same edit and continue for 64 bits as we’ve been able to with 32 bit code for

ages.

Return value inspection To help out the debugging process you can now easily see return values of

functions being used as parameters in other function calls, for example if you nest several functions in

each other.

Just my code this feature tells the debugger to only step through the code you’ve been writing yourself

and ignore frameworks and other code. The system is doing this by looking at open projects, .pbd files

and program optimisations. For .Net Framework, this came before VS 2013, but what’s new now is that

Page 19: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

19 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

it’s available for C++ and JavaScript as well. To enable or disable Just My Code, open Debug -> Options

and Settings -> General and change the value of Enable Just My Code.

Peek a definition It’s now possible to open up a method definition without having to open that specific

file. You can even open up a section located further up/down in your current file without having to leave

the location you are at now. This feature is called Peek Definition and can be accessed through ALT + F12

or by right clicking the method and select Peek Definition. Here is an example where I’m peeking on the

InitializeComponent () method.

CodeMap – Visual Debugging: When you are in Debug mode, clicking this will open a window which

shows the visual representation of the execution flow

Code Lens

You won’t miss noting this feature when using Visual Studio 2013. There will be indicators sitting atop of

every method in the code editor.

About Garbage Collector?

In the common language runtime (CLR), the garbage collector serves as an automatic memory manager. It provides the following benefits:

Enables you to develop your application without having to free memory. Allocates objects on the managed heap efficiently. Reclaims objects that are no longer being used, clears their memory, and keeps the memory

available for future allocations. Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.

Provides memory safety by making sure that an object cannot use the content of another object.

Conditions for a garbage collection

Garbage collection occurs when one of the following conditions is true:

The system has low physical memory. The memory that is used by allocated objects on the managed heap surpasses an acceptable

threshold. This threshold is continuously adjusted as the process runs. The GC.Collect method is called. In almost all cases, you do not have to call this method,

because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

Generations

Page 20: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

20 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:

Generation 0. This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation. Newly allocated objects form a new generation of objects and are implicitly generation 0 collections, unless they are large objects, in which case they go on the large object heap in a generation 2 collection. Most objects are reclaimed for garbage collection in generation 0 and do not survive to the next generation.

Generation 1. This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.

Generation 2. This generation contains long-lived objects. An example of a long-lived object is an object in a server application that contains static data that is live for the duration of the process.

Garbage collections occur on specific generations as conditions warrant. Collecting a generation means collecting objects in that generation and all its younger generations. A generation 2 garbage collection is also known as a full garbage collection, because it reclaims all objects in all generations (that is, all objects in the managed heap).

Survival and promotions

Objects that are not reclaimed in a garbage collection are known as survivors, and are promoted to the next generation. Objects that survive a generation 0 garbage collection are promoted to generation 1; objects that survive a generation 1 garbage collection are promoted to generation 2; and objects that survive a generation 2 garbage collection remain in generation 2.

When the garbage collector detects that the survival rate is high in a generation, it increases the threshold of allocations for that generation, so the next collection gets a substantial size of reclaimed memory. The CLR continually balances two priorities: not letting an application's working set get too big and not letting the garbage collection take too much time.

About Execution flow of C# Program?

Source code written in C# is compiled into an intermediate language (IL) that conforms to the CLI

specification.

If the security requirements are met, the CLR performs just in time (JIT) compilation to convert the IL

code to native machine instructions

Page 21: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

21 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Hello World! Program?

using System; namespace KnackHook { class Program { static void Main(string[] args) { Console.Write("Hollo World!"); } } }

OutPut:

Page 22: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

22 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About static void Main(string[] args)?

using System; namespace KnackHook { class Program { static void Main(string[] args) { Console.Write("Hollo World!"); } } }

OutPut:

The static keyword tells us that this method should be accessible without instantiating the class.

void, it tells us what this method should return. For instance, int could be an integer or a string of text,

but in this case, we don't want our method to return anything, or void, which is the same as no type.

Main, which is simply the name of our method. This method is the so-called entry-point of our

application, that is, the first piece of code to be executed.

A set of arguments can be specified within a set of parentheses. In our example, our method takes only

one argument, called args. The type of the argument is a string, or to be more precise, an array of

strings, but more on that later. If you think about it, this makes perfect sense, since Windows

applications can always be called with an optimal set of arguments. These arguments will be passed as

text strings to our main method.

About Write, WriteLine, Read, ReadLine and ReadKey methods?

using System; namespace KnackHook { class Program { static void Main(string[] args) { //The Write() method outputs one or more values to the screen without a new line character(\n). Console.Write("About Write!");

Page 23: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

23 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.Write("Hollo World!"); Console.Write("Hollo World!"); //The WriteLine() always appends a new line character to the end of the string. this means any subsequent output will start on a new line.(\n) Console.Write("About WriteLine!"); Console.WriteLine("Hollo World!"); Console.WriteLine("Hollo World!"); //there is no difference b/w Write and WriteLine if we use \n in Write method Console.Write("About Write with \n!"); Console.Write("Hollo World!\n"); Console.Write("Hollo World!\n"); Console.WriteLine("Hollo World!"); Console.WriteLine("Hollo World!"); ////Read() method will read only a single char and return ASCII value of that character Console.Write("About Read!"); int i = Console.Read(); Console.WriteLine(i); ////ReadLine() Method reads the whole string Console.Write("About ReadLine!"); string s = Console.ReadLine(); Console.WriteLine(s); //With ReadKey() we can get ConsoleKey information like what is the key user entered and Modifier information as below Console.WriteLine("Please Enter Something : "); ConsoleKeyInfo obj = Console.ReadKey(); Console.WriteLine(); Console.WriteLine("Key : {0},KeyChar is :{1},Modifier is :{2}", obj.Key, obj.KeyChar.GetTypeCode(), obj.Modifiers.ToString()); Console.ReadLine(); } } }

OutPut:

Page 24: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

24 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Data Types?

Data Types Size Range

Byte 1 Byte 0 to 255

Sbyte 1 Byte -128 to 127

Short 2 Bytes -32,768 to 32,767

Ushort 2 Bytes 0 to 65,535

Int 4 Bytes -2,147,483,648 to 2,147,483,647

Uint 4 Bytes 0 to 4,294,967,295

Long 8 Bytes -9,223,372,036,854,775,808 to

9,223,372,036,854,775,807

Ulong 8 Bytes 0 to 18,446,744,073,709,551,615

Float 4 Bytes -3.402823e38 to 3.402823e38

Double 8 Bytes -1.79769313486232e308 to

1.79769313486232e308

Page 25: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

25 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Decimal 16 Bytes 79228162514264337593543950335 to

79228162514264337593543950335

Char 2 Bytes

Bool 1 Bytes

String

Object

About difference between Decimal, Float and Double in .NET?

Precision is the main difference.

Float - 7 digits (32 bit)

Double-15-16 digits (64 bit)

Decimal -28-29 significant digits (128 bit)

Decimals have much higher precision and are usually used within financial applications that require a

high degree of accuracy. Decimals are much slower (up to 20X times in some tests) than a double/float.

Decimals and Floats/Doubles cannot be compared without a cast whereas Floats and Doubles can.

Decimals also allow the encoding or trailing zeros.

using System; namespace KnackHook { class Program { static void Main(string[] args) { float flt = 1F / 3; double dbl = 1D / 3; decimal dcm = 1M / 3; Console.WriteLine("float: {0} double: {1} decimal: {2}", flt, dbl, dcm);

Page 26: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

26 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.ReadLine(); } } }

OutPut:

How to get Max and Min range of data types?

using System; namespace KnackHook { class Program { static void Main(string[] args) { ////Built-in Data Types: //byte ////How to find the Min and Max values of a data type Console.WriteLine("The minimum value of byte is {0},maximam value of byte is {1}", byte.MinValue, byte.MaxValue); ////How to find size data type Console.WriteLine("The size of of byte is {0}", sizeof(byte)); //short Console.WriteLine("The minimum value of short is {0},maximam value of short is {1}", short.MinValue, short.MaxValue); Console.WriteLine("The size of of short is {0}", sizeof(short)); //int Console.WriteLine("Interger Min Value:" + sbyte.MinValue + " Integer Max Value:" + sbyte.MaxValue); Console.ReadLine(); } } }

OutPut:

Page 27: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

27 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Data type conversion?

Implicit conversions: No special syntax is required because the conversion is type safe and no

data will be lost. Examples include conversions from smaller to larger integral types, and

conversions from derived classes to base classes.

Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required

when information might be lost in the conversion, or when the conversion might not succeed

for other reasons. Typical examples include numeric conversion to a type that has less precision

or a smaller range, and conversion of a base-class instance to a derived class.

User-defined conversions: User-defined conversions are performed by special methods that you

can define to enable explicit and implicit conversions between custom types that do not have a

base class–derived class relationship.

Conversions with helper classes: To convert between non-compatible types, such as integers

and Sytems.DateTime objects, or hexadecimal strings and byte arrays, you can use the

Syste.BitConvmerter class, the System.Convert class, and the Parse methods of the built-

in numeric types, such as Int32.Parse.

using System; namespace KnackHook { class Program { static void Main(string[] args) {

Page 28: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

28 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//Type Coversion //Implicit Type Conversion:Converting lower data type value to higher data type value int intValue = 123; long longValue = intValue; Console.WriteLine("{0}, {1}", intValue, longValue); Console.ReadLine(); ////Explicit Type Conversion:Converting higher data type value to lower data type value double doubleValue = 123.13; int intValue1 = Convert.ToInt32(doubleValue); Console.WriteLine("{0}, {1}", doubleValue, intValue1); Console.ReadLine(); } } }

OutPut:

About Boxing and Unboxing?

Boxing is the process of converting a value type to the type object or to any interface type implemented

by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and

stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit;

unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type

system in which a value of any type can be treated as an object.

Page 29: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

29 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Unboxing is an explicit conversion from the type object to a value type or from an interface type to a

value type that implements the interface. An unboxing operation consists of:

Checking the object instance to make sure that it is a boxed value of the given value type.

Copying the value from the instance into the value-type variable.

using System; namespace KnackHook { class Program { static void Main(string[] args) { ////Boxing and Unboxing int stackVar = 12;

Page 30: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

30 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//Boxing: Converting value type to reference type object boxedVar = stackVar; //Unboxing: Converting reference type to value type int unBoxed = (int)boxedVar; Console.WriteLine("{0}, {1}", boxedVar, unBoxed); Console.ReadLine(); } } }

OutPut:

About Operators?

Assignment Operators like =

Arithmetic Operators like +,-,*,/,%

Comparison Operators like ==,!=,>,<,<=,>=

Conditional Operators like &&,||

Ternary Operators like ?,:

Null Coalescing Operators like ??

Bitwise Operators

IS and AS Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical

manipulations. C# has rich set of built-in operators and provides the following type of operators:

Arithmetic Operators

Operator Description Example

+ Adds two operands A + B = 30

- Subtracts second operand from the first A - B = -10

* Multiplies both operands A * B = 200

/ Divides numerator by de-numerator B / A = 2

Page 31: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

31 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

% Modulus Operator and remainder of after an

integer division B % A = 0

++ Increment operator increases integer value by

one A++ = 11

-- Decrement operator decreases integer value by

one A-- = 9

Relational Operators

Operator Description Example

== Checks if the values of two operands are equal or

not, if yes then condition becomes true. (A == B) is not true.

!=

Checks if the values of two operands are equal or

not, if values are not equal then condition

becomes true.

(A != B) is true.

>

Checks if the value of left operand is greater than

the value of right operand, if yes then condition

becomes true.

(A > B) is not true.

<

Checks if the value of left operand is less than the

value of right operand, if yes then condition

becomes true.

(A < B) is true.

>=

Checks if the value of left operand is greater than

or equal to the value of right operand, if yes then

condition becomes true.

(A >= B) is not true.

<=

Checks if the value of left operand is less than or

equal to the value of right operand, if yes then

condition becomes true.

(A <= B) is true.

Page 32: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

32 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Logical Operators

Operator Description Example

&& Called Logical AND operator. If both the operands

are non zero then condition becomes true. (A && B) is false.

||

Called Logical OR Operator. If any of the two

operands is non zero then condition becomes

true.

(A || B) is true.

!

Called Logical NOT Operator. Use to reverses the

logical state of its operand. If a condition is true

then Logical NOT operator will make false.

!(A && B) is true.

Bitwise Operators

Assignment Operators

Misc Operators

Category

Symbol

Sign operators + -

Arithmetic + - * / %

Logical (boolean and bitwise) & | ^ ! ~ && || true false

String concatenation +

Increment, decrement ++ --

Page 33: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

33 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Shift <<>>

Relational == != <><= >=

Assignment = += -= *= /= %= &= |= ^= <<= >>=

Member access .

Indexing []

Cast ()

Ternary ?:

Delegate concatenation and removal + -

Object creation new

Type information as is sizeof typeof

Overflow exception control checked unchecked

Indirection and address * -> [] &

Lambda =>

About Ternary Operator?

Conditional Operator (Ternary Operator) is used to Return one value if the condition is true, or another

value if it is false. Ternary Operator, the idea behind, can assign value to a variable according to the

condition with selecting one value from two variables. It is some sort of if-else code in a short form.

using System;

namespace KnackHook { class Program { static void Main(string[] args) { //Ternary Operators //If the expression is true, set value to “Eligible”.Otherwise, set value to “Not Eligible”. int age = 25; string IsEligibleForVote = age>18 ? "Eligible" : "Not Eligible"; Console.WriteLine(IsEligibleForVote); Console.ReadLine();

Page 34: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

34 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} } }

OutPut:

About is and as Operators?

is operator

The is operator in C# is used to check the object type and it returns a bool value: true if the object is the

same type and false if not.

For null objects, it returns false.

Syntax: bool isobject = (Object is Type);

as operator

The as operator does the same job of is operator but the difference is instead of bool, it returns the

object if they are compatible to that type, else it returns null.

Syntax: Type obj = Object as Type;

using System; namespace KnackHook { class Abc { } class Def { } class Program

Page 35: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

35 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{ static void Main(string[] args) { //is and as Operators //The is operator in C# is used to check the object type and it returns a bool value: true if the object is the same type and false if not. Abc A = new Abc(); Def D = new Def(); bool isDef = (A is Def); Console.WriteLine(isDef); //The as operator does the same job of is operator but the difference is instead of bool, it returns the object if they are compatible to that type, else it returns null. Def isDefType = D as Def; Console.WriteLine(isDefType); Console.ReadLine(); Console.ReadLine(); } } }

OutPut:

About Null Coalescing Operator “??” ?

Null coalescing. The null coalescing operator "??" uses two question marks. With it you can use a

custom value for a null reference variable. It simplifies null tests.

Null conditional. Similar to the coalescing operator, the null conditional operator tests for null before

accessing a member of an instance

Page 36: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

36 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System; namespace KnackHook { class Program { static void Main(string[] args) { //Null Coalescing Operators :?? //The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand. int? x = null; // Set y to the value of x if x is NOT null; otherwise, // if x = null, set y to -1. int y = x ?? -1; Console.WriteLine(y); Console.ReadLine(); } } }

OutPut:

About Bitwise Operators?

Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as

follows:

p Q p & q p | q p ^ q

0 0 0 0 0

Page 37: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

37 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; then in the binary format they are as follows:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100=12

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

Example:

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { class Program { static void Main(string[] args) { int A = 60;//0011 1100 int B = 13;//0000 1101 Console.WriteLine("The bitwise & value of A&B is {0}",A&B);//12 Console.WriteLine("The bitwise | value of A|B is {0}", A | B);//49

Page 38: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

38 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine("The bitwise ^ value of A^B is {0}", A ^ B);//61 Console.WriteLine("The bitwise << value of A<< is {0}", A << B);//491520 Console.WriteLine("The bitwise >> value of A>>B is {0}", A >> B);//0 Console.WriteLine("The bitwise ~ value of ~A is {0}", ~A);//-61 Console.ReadLine(); } } }

OutPut:

About difference between int.Parse,Convert.ToInt32 and int.TryParse? int.Parse:

Simply, int.Parse (string s) method converts the string to integer. If string s is null,

then it will throw ArgumentNullException. If string s is other than integer value, then it will

throw FormatException. If string s represents out of integer ranges, then it will

throw OverflowException.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { class Program { static void Main(string[] args) { string str1 = "9009"; string str2 = null; string str3 = "9009.9090800"; string str4 = "90909809099090909900900909090909"; int finalResult; finalResult = int.Parse(str1); //success

Page 39: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

39 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

finalResult = int.Parse(str2); //ArgumentNullException finalResult = int.Parse(str3); //FormatException finalResult = int.Parse(str4); //OverflowException Console.ReadLine(); } } }

OutPut:

Convert.ToInt32:

Simply, Convert.ToInt32(string s) method converts the string to integer. If string s is null, then it will return 0 rather than throw ArgumentNullException. If string s is other than integer value, then it will throw FormatException. If string s represents out of integer ranges, then it will throwOverflowException.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { class Program { static void Main(string[] args) { string str1 = "9009"; string str2 = null; string str3 = "9009.9090800"; string str4 = "90909809099090909900900909090909"; int finalResult; finalResult = Convert.ToInt32(str1); // 9009 finalResult = Convert.ToInt32(str2); // 0 finalResult = Convert.ToInt32(str3); //FormatException

Page 40: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

40 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

finalResult = Convert.ToInt32(str4); //OverflowException Console.ReadLine(); } } } int.TryParse:

Simply int.TryParse(string s,out int) method converts the string to integer out variable and returnstrue if successfully parsed, otherwise false. If string s is null, then the out variable has 0 rather than throw ArgumentNullException. If string s is other than integer value, then the out variable will have 0rather than FormatException. If string s represents out of integer ranges, then the out variable will have 0rather than throw OverflowException.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { class Program { static void Main(string[] args) { string str1 = "9009"; string str2 = null; string str3 = "9009.9090800"; string str4 = "90909809099090909900900909090909"; int finalResult; bool output; output = int.TryParse(str1, out finalResult); // 9009 output = int.TryParse(str2, out finalResult); // 0 output = int.TryParse(str3, out finalResult); // 0 output = int.TryParse(str4, out finalResult); // 0 Console.ReadLine(); } } }

Conditional Statements?

Page 41: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

41 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Conditional Statements

IF IF ELSE

FOR WHILE

DO WHILE SWITCH

FOREACH

About if? if conditional statement is used to evaluate single condition

namespace KnackHook { class Program { static void Main(string[] args) { int Age = 30; //if conditional statement is used to evaluate single condition if (Age >18 ) Console.WriteLine("Eligible for vote!"); } } }

About if-else?

if-else conditional statement is used to evaluate two condition

namespace KnackHook { class Program { static void Main(string[] args) { int Age = 30; //if-else conditional statement is used to evaluate two condition if (Age >18 ) Console.WriteLine("Eligible for vote!"); else

Page 42: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

42 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine("Not Eligible for vote!"); } } }

About switch vs if-else-if?

Sometimes we need to use a sequence of if structures, where the else clause is a new if structure. If we

use nested if structures, the code would be pushed too far to the write. That’s why in such situations it

is allowed to use a new if right after the else.

The structure switch-case chooses which part of the programming code to execute based on the calculated value of a certain expression (most often of integer type). using System; namespace KnackHook { class Program { static void Main(string[] args) { //use of switch statement compare to if-else statement string DayName = "Wednesday"; //if else if if (DayName == "Sunday") Console.WriteLine("The Day is Sunday"); else if (DayName == "Monday") Console.WriteLine("The Day is Monday"); else if (DayName == "Monday") Console.WriteLine("The Day is Monday"); else if (DayName == "Tuesday") Console.WriteLine("The Day is Tuesday"); else if (DayName == "Wednesday") Console.WriteLine("The Day is Wednesday"); else if (DayName == "Thursday") Console.WriteLine("The Day is Thursday"); else if (DayName == "Friday") Console.WriteLine("The Day is Friday"); else if (DayName == "Saturday") Console.WriteLine("The Day is Saturday"); else Console.WriteLine("Please enter proper day"); Console.ReadLine(); //switch: which provides an easy way to check multiple statements

Page 43: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

43 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

switch (DayName) { case "Sunday": Console.WriteLine("The Day is Sunday"); break; case "Monday": Console.WriteLine("The Day is Monday"); break; case "Tuesday": Console.WriteLine("The Day is Tuesday"); break; case "Wednesday": Console.WriteLine("The Day is Wednesday"); break; case "Thursday": Console.WriteLine("The Day is Thursday"); break; case "Friday": Console.WriteLine("The Day is Friday"); break; case "Saturday": Console.WriteLine("The Day is Saturday"); break; default: Console.WriteLine("Please enter proper day"); break; } Console.ReadLine(); } } }

OutPut:

About for vs foreach?

Page 44: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

44 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

For and foreach differ slightly in performance. They are approximately the same speed. But the foreach

loop uses more stack space for local variables.

Foreach. A program iterates over a collection. The index of each element is not needed. Only the

elements are needed. With foreach we access just the elements.

With no indexes, loops are easier to write. Programs are simpler. They are clearer. Many language

features (like query expressions) work well with foreach.

A foreach-loop. This is the easiest, least error-prone loop. It is preferred in many program contexts. But

we lose some flexibility with it.

Index: Foreach uses no integer index. Instead, it is used on a collection—it returns each element in

order.

using System; namespace KnackHook { class Program { static void Main(string[] args) { //for vs foreach //foreach-which is useful to iterate through collections very easily int[] myInterger = new int[4]; myInterger[0] = 1; myInterger[1] = 2; myInterger[2] = 3; myInterger[3] = 4; int total = 0; foreach (int i in myInterger) { total += i; } Console.WriteLine(total); Console.ReadLine(); ////Same using For for (int i = 0; i < myInterger.Length; i++) { total += myInterger[i]; ; } Console.WriteLine(total); Console.ReadLine(); } } }

Page 45: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

45 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

OutPut:

About while vs do-while?

The C# while statement executes a statement or a block of statements until a specified expression

evaluates to false. In some situation you may want to execute the loop at least one time and then check

the condition. In this case you can use do while loop.

The difference between do while and while is that do while evaluates its expression at the bottom of

the loop instead of the top. Therefore, the statements within the do block are always executed at least

once. From the following example you can understand how do while loop function.

namespace KnackHook { class Program { static void Main(string[] args) { int[] myInterger = new int[4]; myInterger[0] = 1; myInterger[1] = 2; myInterger[2] = 3; myInterger[3] = 4; int total = 0; //While int i = 0; while (i < myInterger.Length) { total += myInterger[i]; i++; } Console.WriteLine("Total from While: " + total); //do While total = 0;

Page 46: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

46 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

int j = 0; do { total += myInterger[j]; j++; } while (j < myInterger.Length); Console.WriteLine("Total from Do-While: " + total); Console.ReadLine(); } } }

Output:

About polyndrome number?

using System; namespace KnackHook { class Program { static void Main(string[] args) { //polyndrome is number which is same as it’s reverse int num, temp, remainder, reverse = 0; Console.WriteLine("Enter an integer \n"); num = int.Parse(Console.ReadLine()); temp = num; while (num > 0) { remainder = num % 10; reverse = reverse * 10 + remainder; num /= 10; } Console.WriteLine("Given number is = {0}", temp); Console.WriteLine("Its reverse is = {0}", reverse);

Page 47: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

47 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

if (temp == reverse) Console.WriteLine("Number is a palindrome \n"); else Console.WriteLine("Number is not a palindrome \n"); Console.ReadLine(); } } }

OutPut:

About Prime number?

using System; namespace KnackHook { class Program { static void Main(string[] args) { //Prime Numbers Console.Write("Enter a Number : "); int num; num = Convert.ToInt32(Console.ReadLine()); int k; k = 0; for (int i = 1; i <= num; i++) { if (num % i == 0) { k++; } } if (k == 2) { Console.WriteLine("Entered Number is a Prime Number and the Largest Factor is {0}", num); } else { Console.WriteLine("Not a Prime Number");

Page 48: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

48 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} Console.ReadLine(); } } }

OutPut:

About Methods?

A method is a group of statements that together perform a task. Every C# program has at least one class

with a method named Main.

To use a method, you need to:

Define the method

Call the method

Defining Methods in C#

When you define a method, you basically declare the elements of its structure. The syntax for

defining a method in C# is as follows:

<Access Specifier><Return Type><Method Name>(Parameter List)

{

Method Body

}

Following are the various elements of a method:

Access Specifier: This determines the visibility of a variable or a method from another class.

Page 49: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

49 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Return type: A method may return a value. The return type is the data type of the value the

method returns. If the method is not returning any values, then the return type is void.

Method name: Method name is a unique identifier and it is case sensitive. It cannot be same as

any other identifier declared in the class.

Parameter list: Enclosed between parentheses, the parameters are used to pass and receive

data from a method. The parameter list refers to the type, order, and number of the parameters

of a method. Parameters are optional; that is, a method may contain no parameters.

Method body: This contains the set of instructions needed to complete the required activity.

About Instance method?

An instance method operates on a given instance of a class, and that instance can be accessed as this.

When a method declaration includes a static modifier, that method is said to be a static method. When

no static modifier is present, the method is said to be an instance method.

using System; namespace KnackHook { class Program { static void Main(string[] args) { ////Methods //Instance Method: which needs an object to call a method Program ojVer = new Program(); int c = ojVer.Add(5, 10); Console.WriteLine(c); Console.ReadLine(); } public int Add(int a, int b) { return a + b; } } }

Page 50: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

50 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

OutPut:

About Static Method?

When a method declaration includes a static modifier, that method is said to be a static method. When

no static modifier is present, the method is said to be an instance method.

A static method does not operate on a specific instance, and it is a compile-time error to refer to this in

a static method.

using System; namespace KnackHook { class Program { static void Main(string[] args) { ////Methods ////Static Method:which doesn't need any object to call a method int d = Add(5, 10); Console.WriteLine(d); Console.ReadLine(); } public static int Add(int a, int b) { return a + b; } } }

OutPut:

Page 51: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

51 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About value type parameters?

There are two ways to allocating space in memory. One is value type and another is Reference type.

When you create int, char or float type variable, it creates value type memory allocation whereas when

you create object of class, it creates reference type memory allocation.

Value Type: A value type variable directly contains data in the memory.

In value type parameter, the actual value gets passed to the function. Passing a value type variable as

parameter means, you are passing the copy of the value.

using System; namespace KnackHook { class Program { static void Main(string[] args) { ////Method Parameters ////Value Parameter: the value changes in called method not reflecting to calling method int i = 10; Console.WriteLine("I value before Calling SimpleMethod() " + i); SimpleMethod(i); Console.WriteLine("I value after Calling SimpleMethod() " + i); Console.ReadLine(); } static void SimpleMethod(int j) { j = j + 1; Console.WriteLine("J value inside Called Method is " + j); } } }

OutPut:

Page 52: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

52 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About reference type parameter?

Reference Type: A Reference type variable contains memory address of value.

The Reference type variable is such type of variable in C# that holds the reference of memory address

instead of value. Class, interface, delegate, array are the reference type. When you create object of

particular class with new keyword, a space is created in the managed heap that holds the reference of

classes.

If you are passing reference type variable as parameter, then you will have to use ref keyword with

variable.

using System; namespace KnackHook { class Program { static void Main(string[] args) { ////Method Parameters ////reference Parameter:the value changes in called method automatically reflecting to calling method int i = 10; Console.WriteLine("I value before Calling SimpleMethodRef() " + i); SimpleMethodRef(ref i); Console.WriteLine("I value after Calling SimpleMethodRef() " + i); Console.ReadLine(); } static void SimpleMethodRef(ref int j) { j = j + 1; Console.WriteLine("J value inside Called Method is " + j); } } }

OutPut:

Page 53: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

53 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About out parameter?

A return statement can be used for returning only one value from a function. However, using output

parameters, you can return two values from a function. Output parameters are similar to reference

parameters, except that they transfer data out of the method rather than into it.

The variable supplied for the output parameter need not be assigned a value. Output parameters are

particularly useful when you need to return values from a method through the parameters without

assigning an initial value to the parameter.

using System; namespace KnackHook { class Program { static void Main(string[] args) { ////Method Parameters ////Out Parameter:which returns more than one value to calling function int i = 5; int j = 5; int Sum = 0; int product = 0; SimpleMethodOut(i, j, out Sum, out product); Console.WriteLine("Sum is {0} and Product is {1}", Sum, product); Console.ReadLine(); } static void SimpleMethodOut(int i, int j, out int Sum, out int Product) { Sum = i + j; Product = i * j; } } }

OutPut:

Page 54: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

54 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About parameter array?

A parameter declared with a params modifier is a parameter array. If a formal parameter list includes a

parameter array, it must be the last parameter in the list and it must be of a single-dimensional array

type. For example, the types string[] and string[][] can be used as the type of a parameter array, but the

type string[,] cannot. It is not possible to combine the params modifier with the modifiers ref and out.

A parameter array permits arguments to be specified in one of two ways in a method invocation:

The argument given for a parameter array can be a single expression of a type that is implicitly

convertible to the parameter array type. In this case, the parameter array acts precisely like a

value parameter.

Alternatively, the invocation can specify zero or more arguments for the parameter array, where

each argument is an expression of a type that is implicitly convertible to the element type of the

parameter array. In this case, the invocation creates an instance of the parameter array type

with a length corresponding to the number of arguments, initializes the elements of the array

instance with the given argument values, and uses the newly created array instance as the

actual argument.

using System; namespace KnackHook { class Program { static void Main(string[] args) { ////Method Parameters ////Parameter Array:which accepts any number of parameters in the form of array SimpleMethodParams(1, 2, 3, 4, 5); Console.ReadLine(); } static void SimpleMethodParams(params int[] numbers)

Page 55: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

55 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{ int sum = 0; foreach (var item in numbers) { sum += item; } Console.WriteLine("Sum of first 5 numbers is {0}", sum); } } }

Output:

About Arrays?

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.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one

array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent

individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element

and the highest address to the last element.

Declaring Arrays

To declare an array in C#, you can use the following

Page 56: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

56 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

syntax: datatype[] arrayName;

Initializing an Array

Declaring an array does not initialize the array in the memory. When the array variable is initialized,

you can assign values to the array.

Array is a reference type, so you need to use the new keyword to create an instance of the array. For

example,

double[] balance = new double[10];

Assigning Values to an Array

You can assign values to individual array elements, by using the index number, like:

double[] balance = new double[10];

balance[0] = 4500.0;

About storing different data types values in to an array?

using System; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //storing different data types values into an array,using object array we can able to achieve it object[] arr = new object[4]; arr[0]="KnackHook"; arr[1]=5; arr[2]= 5.55; arr[3]='K'; foreach (var item in arr) { Console.WriteLine(item); } Console.ReadLine(); }

Page 57: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

57 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} }

About Obsolete Attribute in C#?

Obsolete. The Obsolete attribute generates a compile-time warning. When a method has the Obsolete

attribute, the C# compiler issues a warning if it is called. This helps keep programs correct. This makes it

easier to transition from old methods.

Example. To begin, the Obsolete attribute is found in the System namespace. It is an attribute type,

which means you can specify the type as Obsolete or ObsoleteAttribute. The suffix "Attribute" is

automatically added at compile-time.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //Obsolete attribute is used to declare a method as deprecated. class Program { static void Main(string[] args) { M1(); M2(); Console.ReadLine(); } [Obsolete("M1() Method is deprecated please use M2() instead")]//it will allow to compile the code with deprecate method //[Obsolete("M1() Method is deprecated please use M2() instead",true)]//it will not allow to compile the code with deprecate method public static void M1() { Console.WriteLine("M1"); } public static void M2() { Console.WriteLine("M2");

Page 58: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

58 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} } }

About Tuple in C#?

A tuple is an ordered sequence, immutable, fixed-size and of heterogeneous objects, i.e., each object

being of a specific type.

Tuple. A Tuple has many items. Each item can have any type. The Tuple class provides a unified syntax

for creating objects with typed fields.

Once created, the fields in the Tuple cannot be mutated. A program can assume a tuple will never

change, so it can be reused. Tuple is a useful generic class.

3 items. Please note that the Tuple type is a class. Once we create the Tuple, we cannot change the

values of its fields. This makes the Tuple more like a string.

Next:In this example, we create a three-item tuple using the special constructor syntax.

And:We then read the Item1, Item2 and Item3 properties. We do not modify them

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //Obsolete attribute is used to declare a method as deprecated. class Program { static void Main(string[] args) { //usage of Tuple var primes = Tuple.Create(2, 3, 5, 7, 11, 13, 17, 19); Console.WriteLine("Prime numbers less than 20: " + "{0}, {1}, {2}, {3}, {4}, {5}, {6}, and {7}",

Page 59: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

59 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

primes.Item1, primes.Item2, primes.Item3, primes.Item4, primes.Item5, primes.Item6, primes.Item7, primes.Rest.Item1); //use tuple to return more that one value from a method Tuple<int, int, int> OperationResult = Calculate(10, 20); Console.WriteLine("Sum is {0} Sub is {1} Mul is {2}", OperationResult.Item1, OperationResult.Item2, OperationResult.Item3); Console.ReadLine(); } public static Tuple<int, int, int> Calculate(int a, int b) { Tuple<int, int, int> vals = Tuple.Create(a+b, a-b, a*b); return vals; } } }

About Finalize and Dispose Methods?

Dispose:

Garbage collector (GC) plays the main and important role in .NET for memory management so

programmer can focus on the application functionality. Garbage collector is responsible for releasing the

memory (objects) that is not being used by the application. But GC has limitation that, it can reclaim or

release only memory which is used by managed resources. There are a couple of resources which GC is

not able to release as it doesn't have information that, how to claim memory from those resources like

File handlers, window handlers, network sockets, database connections etc. If your application these

resources than it's programs responsibility to release unmanaged resources. For example, if we open a

file in our program and not closed it after processing than that file will not be available for other

operation or it is being used by other application than they can not open or modify that file. For this

purpose FileStream class provides Dispose method. We must call this method after file processing

finished. Otherwise it will through exception Access Denied or file is being used by other program.

Page 60: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

60 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Close Vs Dispose

Some objects expose Close and Dispose two methods. For Stream classes both serve the same purpose.

Dispose method calls Close method inside.

void Dispose()

{

this.Close();

}

Finalize: Finalize method also called destructor to the class. Finalize method can not be called explicitly in the

code. Only Garbage collector can call the the Finalize when object become inaccessible. Finalize method

cannot be implemented directly it can only be implement via declaring destructor. Following class

illustrate, how to declare destructor. It is recommend that implement Finalize and Dispose method

together if you need to implement Finalize method. After compilation destructor becomes Finalize

method

Finalize is bit expensive to use. It doesn't clean the memory immediately. When application runs,

Garbage collector maintains a separate queue/array when it adds all object which has finalized

implemented. Other term GC knows which object has Finalize implemented. When the object is ready to

claim memory, Garbage Collector call finalize method for that object and remove from the collection. In

this process it just clean the memory that used by unmanaged resource. Memory used by managed

resource still in heap as inaccessible reference. That memory release, whenever Garbage Collector run

next time. Due to finalize method GC will not clear entire memory associated with object in fist attempt.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { //Finalize() belongs to the Object class. //It is automatically called by the Garbage Collection mechanism when the object goes out of the scope(usually at the end of the program //It is slower method and not suitable for instant disposing of the objects. //It is non-deterministic function i.e., it is uncertain when Garbage Collector will call Finalize() method to reclaim memory. class employee:IDisposable {

Page 61: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

61 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

~employee() { //This is the destructor of emp class //This destructor is implicitly compiled to the Finalize method. } //Explicitly, it is called by user code and the class implementing dispose method must implement IDisposable interface. //used to release unmanaged code. public void Dispose() { Dispose(); GC.SuppressFinalize(this); } } class Program { static void Main(string[] args) { SqlConnection sqlcon=null; try { string constring = "Server=(local);Database=my; User Id=sa; Password=sa"; sqlcon = new SqlConnection(constring); sqlcon.Open(); // here connection is open } catch { } finally { sqlcon.Close(); // close the connection sqlcon.Dispose(); // detsroy the connection object } Console.ReadLine(); } } }

About using keyword?

Page 62: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

62 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The using statement is mostly used to handle any managed object that implements the IDisposable

interface.

At that time, we use Structured Exception Handling to ensure that the Dispose() of IDisposable interface

implemented in your class is called.

When you are using an object that encapsulates any resource, you have to make sure that when you are

done with the object, the object's Dispose method is called. This can be done more easily using the using

statement in C#. The using statement simplifies the code that you have to write to create and then finally

clean up the object. The using statement obtains the resource specified, executes the statements and

finally calls the Dispose method of the object to clean up the object.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { //"using" keyword helps to clear objects once execution come out of the using block. //"using" keyword helps to import namespaces. class Program { static void Main(string[] args) { using (SqlConnection sqlcon = new SqlConnection()) { sqlcon.Open(); } Console.ReadLine(); } } }

About Use of New Keyword?

When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from

a base class. When you hide an inherited member, the derived version of the member replaces the base

Page 63: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

63 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

class version. Although you can hide members without using the new modifier, you get a compiler

warning. If you use new to explicitly hide a member, it suppresses this warning.

To hide an inherited member, declare it in the derived class by using the same member name, and

modify it with the new keyword.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { //"New" keyword helps to hide base class method and provides new implemetation in derived class. class A { public void show() { Console.WriteLine("Hello: Base Class!"); } } class B : A { public new void show() { Console.WriteLine("Hello: Derived Class!"); } } class Program { static void Main(string[] args) { A a1 = new A(); a1.show(); B b1 = new B(); b1.show(); A a2 = new B(); a2.show(); Console.ReadLine(); }

Page 64: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

64 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} }

About sorting an array elements?

To sort array of primitive types such as int, double or string use method Array.Sort(Array) with the array

as a paramater. The primitive types implements interface IComparable, which is internally used by the

Sort method (it calls IComparable.CompareTo method).

using System; namespace KnackHook { class Program { static void Main(string[] args) { //Sorting an array elements int[] arr = new int[5]; arr[0] = 10; arr[1] = 14; arr[2] = 15; arr[3] = 14; arr[4] = 11; Console.WriteLine("Array elements before sorting"); foreach (var item in arr) { Console.WriteLine(item); } Array.Sort(arr); Console.WriteLine("Array elements after sorting"); foreach (var item in arr) { Console.WriteLine(item); } Console.ReadLine(); } } }

About sorting elements with Bubble sort?

Page 65: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

65 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Bubble Sort is a sorting algorithm (an algorithm that puts elements of a list in a certain order). The

simplest sorting algorithm is Bubble Sort. In the Bubble Sort, as elements are sorted they gradually

"bubble up" to their proper location in the array, like bubbles rising in a glass of soda.

The Bubble Sort works by iterating down an array to be sorted from the first element to the last,

comparing each pair of elements and switching their positions if necessary. This process is repeated as

many times as necessary, until the array is sorted.

using System; namespace KnackHook { class Program { static void Main(string[] args) { //Sorting an array elements using bubble sort int[] arr = new int[5]; arr[0] = 10; arr[1] = 14; arr[2] = 15; arr[3] = 12; arr[4] = 11; int i, j; int N = arr.Length; for (j = N - 1; j > 0; j--) { for (i = 0; i < j; i++) { if (arr[i] > arr[i + 1]) exchange(arr, i, i + 1); } } foreach (var item in arr) { Console.WriteLine(item); } Console.ReadLine(); } public static void exchange(int[] data, int m, int n) { int temporary; temporary = data[m]; data[m] = data[n];

Page 66: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

66 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

data[n] = temporary; } } }

About structures?

A structure in C# is simply a composite data type consisting of a number elements of other types. A C#

structure is a value type and the instances or objects of a structure are created in stack. The structure in

C# can contain fields, methods, constants, constructors, properties, indexers, operators and even other

structure types.

Structure Declaration & Object Creation

The keyword struct can be used to declare a structure. The general form of a structure declaration in C#

is as follows.

<modifiers> struct <struct_name>

{

//Structure members

}

Where the modifier can be private, public, internal or public. The struct is the required keyword.

Structs & Fields

A struct in C# can contain fields. These fields can be declared as private, public, internal. Remember that

inside a struct, we can only declare a field. We can't initialize a field inside a struct. However we can use

constructor to initialize the structure fields.

struct can contain static fields, which can be initialized inside the struct.

Remember that static fields can't be accessed by an instance of a struct. We can access them only by

using the struct names.

The methods inside a struct can also be overloaded as like inside a class

Page 67: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

67 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Structs & Constructors

A C# struct can declare constrcutor, but they must take parameters. A default constructor (constructor

without any parameters) are always provided to initialize the struct fields to their default values.

The parameterized constructors inside a struct can also be overloaded.

Finally remember that C# struct do not support destructors.

using System; namespace KnackHook { public struct Customer { private int id; public int Id { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } public Customer(int Ids, string name) { this.id = Ids; this.name = name; } public void Print() { Console.WriteLine(id + name); Console.ReadLine(); } } class Program { static void Main(string[] args) {

Page 68: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

68 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//Structures/ Structs //Similar to classes struct can have fields, properties,constructors and methods. //Class is Reference type but Struct is Value type //Struct can't have desructors //Struct can't be inherite Customer c = new Customer(101, "Madhan"); c.Print(); Console.ReadLine(); } } }

About enum data type?

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named

constants called the enumerator list.

Usually it is best to define an enum directly within a namespace so that all classes in the namespace can

access it with equal convenience. However, an enum can also be nested within a class or struct.

By default, the first enumerator has the value 0, and the value of each successive enumerator is

increased by 1. For example, in the following enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth.

Enumerators can use initializers to override the default values

Every enumeration type has an underlying type, which can be any integral type except char. The default

underlying type of enumeration elements is int. To declare an enum of another integral type, such as

byte, use a colon after the identifier followed by the type, as shown in the following example.

enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

using System; namespace KnackHook { //enum 0 1 2 3 4 5 6 public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; class Program

Page 69: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

69 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{ static void Main(string[] args) { //Enums //Enums are strongly typed constants //The default underlying type an enum is int. //Th default value of the enum is 0 and increment by 1. //Enum is value type Console.WriteLine((int)Days.Sun); Console.WriteLine((int)Days.Mon); Console.WriteLine((int)Days.Tue); Console.WriteLine((int)Days.Wed); Console.WriteLine((int)Days.Thu); Console.WriteLine((int)Days.Fri); Console.WriteLine((int)Days.Sat); Console.ReadLine(); } } }

About reversing a string?

using System; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //method one string str = "KnackHook"; char[] strrev = str.ToCharArray(); Array.Reverse(strrev); Console.WriteLine("Reverse of a string is {0}", new string(strrev)); //method 2 string str1 = "KnackHook"; StringBuilder strtemp = new StringBuilder(); char[] strrev1 = str1.ToCharArray(); Array.Reverse(strrev1);

Page 70: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

70 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

foreach (var item in strrev1) { strtemp.Append(item); } Console.WriteLine("Reverse of a string is {0}", strtemp); Console.ReadLine(); } } }

About string vs stringbuilder?

String

String is immutable. Immutable means once we create string object we cannot modify. Any operation

like insert, replace or append happened to change string simply it will discard the old value and it will

create new instance in memory to hold the new value.

String Builder

String builder is mutable it means once we create string builder object we can perform any operation

like insert, replace or append without creating new instance for every time.

String StringBuilder

It’s an immutable It’s mutable

Performance wise string is slow because every time it

will create new instance

Performance wise stringbuilder is high because it will

use same instance of object to perform any action

In string we don’t have append keyword In StringBuilder we can use append keyword

String belongs to System namespace Stringbuilder belongs to System.Text namespace

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging;

Page 71: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

71 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System.Reflection; using System.Threading; namespace KnackHook { class Program { static void Main(string[] args) { //string is a immutal //Performance wise string is slow because every time it will create new instance //String belongs to System namespace string str = "KnackHook"; // create a new string instance instead of changing the old one str += " IT"; str += " Services"; Console.WriteLine("The complete Name is {0}",str); //StringBuilder mutable //Performance wise stringbuilder is high because it will use same instance of object to perform any action //Stringbuilder belongs to System.Text namespace StringBuilder str1 = new StringBuilder(); str1.Append("KnackHook"); str1.Append(" IT"); str1.Append(" Services"); Console.WriteLine("The complete Name is {0}", str1); Console.ReadLine(); } } }

OutPut:

About Difference b/w .ToString() and Convert.ToString()?

We can convert the integer “i” using “i.ToString()” or “Convert.ToString” so what is the difference. The

basic difference between them is “Convert” function handles NULLS while “i.ToString()” does not it will

throw a NULL reference exception error. So as a good coding practice using “convert” is always safe.

Page 72: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

72 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

OutPut1: Incase of uncommented str2;

OutPut2: Incase of commented str2;

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { class Program { static void Main(string[] args) { //.ToString() not allow null,it gives error string str1 = "KnackHook"; Console.WriteLine(str1.ToString());//will work fine string str2 = null; Console.WriteLine(str2.ToString());//will give System.NullReferenceException //.ToString() not allow null,it gives error string str3 = "KnackHook"; Console.WriteLine(Convert.ToString(str3));//will work fine string str4 = null; Console.WriteLine(Convert.ToString(str4));//will work fine Console.ReadLine(); } } }

Page 73: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

73 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Recursive Method?

Computer programming technique involving the use of a procedure, subroutine, function, or algorithm

that calls itself one or more times until a specified condition is met at which time the rest of each

repetition is processed from the last one called to the first — compare iteration

A method can call itself. This is known as recursion. Following is an example that calculates factorial for a

given number using a recursive function:

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { class Program { static void Main(string[] args) { Program p = new Program(); //calling the factorial method Console.WriteLine("Factorial of 6 is : {0}", p.factorial(6)); Console.WriteLine("Factorial of 7 is : {0}", p.factorial(7)); Console.WriteLine("Factorial of 8 is : {0}", p.factorial(8)); Console.ReadLine(); } public int factorial(int num) { int result; if (num == 1) { return 1; } else { result = factorial(num - 1) * num; return result; } } } }

Page 74: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

74 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

OutPut:

About Collections?

Collection classes are specialized classes for data storage and retrieval. These classes provide support for

stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces.

Collection classes serve various purposes, such as allocating memory dynamically to elements and

accessing a list of items on the basis of an index etc. These classes create collections of objects of the

Object class, which is the base class for all data types in C#.

About ArrayList?

It represents 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.

using System; using System.Collections; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //ArrayList is used to store non-homogeneous data types under a common name ArrayList obj = new ArrayList(); obj.Add("Madhan"); obj.Add(10); obj.Add(10.123);

Page 75: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

75 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

obj.Insert(2,"Mamidala"); foreach (var item in obj) { Console.WriteLine(item); } Console.ReadLine(); } } }

OutPut:

About Hashtable?

It uses a key to access the elements in the collection.

A hash table is used when you need to access elements by using key, and you can identify a

useful key value. Each item in the hash table has a key/value pair. The key is used to access the

items in the collection.

using System; using System.Collections; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //Hashtable is used to store non-homogeneous data types with Kay and Value pairs under a common name Hashtable obj = new Hashtable();

Page 76: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

76 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

obj.Add(1, "Madhan"); obj.Add(2, "Kumar"); obj.Add(3, "Mamidala"); for (int i = 1; i <= obj.Count; i++) { Console.WriteLine("The value for the Kay is {0}", obj[i]); } Console.ReadLine(); } } }

Output:

About Stack?

It represents a last-in, first out collection of object.

It is used when you need a last-in, first-out access of items. When you add an item in the list, it

is called pushing the item and when you remove it, it is called popping the item.

using System; using System.Collections; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //Stack is used to store non-homogeneous data types in First In Last Out(FILO) order under a common name Stack obj = new Stack(); obj.Push("Madhan"); obj.Push("Kumar");

Page 77: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

77 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

obj.Push("Mamidala"); foreach (var item in obj) { Console.WriteLine(item); } Console.ReadLine(); } } }

OutPut:

About Difference b/w Pop() and Peek()?

Pop:

Pop means to remove something from stack. When we want to remove the value from stack only that

value which is at top is removed because as I discussed stack uses a LIFO policy. So the value pushed at

end will remove at first. To pop value from stack, stack class provides us a function named pop (). The

function takes nothing and returns object type value. When the value is pop it is removed from the stack

and the next value becomes the peek value.

Peek:

When we do pop the value at top removes form the stack. But sometimes we do not know that what

value is at top in stack and we do not want to pop it without knowing. So for this purpose we have a

function named peek (). The function takes nothing but it returns object value which is at peek but does

not remove that value like pop function.

using System;

Page 78: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

78 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { class Program { static void Main(string[] args) { // Creates and initializes a new Statck. Stack myS = new Stack(); myS.Push("The"); myS.Push("quick"); myS.Push("brown"); myS.Push("fox"); // Displays the Stack. Console.Write("Stack values:"); PrintValues(myS); // Removes an element from the Stack. Console.WriteLine("(Pop)\t{0}", myS.Pop()); // Displays the Stack. Console.Write("Stack values:"); PrintValues(myS); // Removes another element from the Stack. Console.WriteLine("(Dequeue)\t{0}", myS.Pop()); // Displays the Stack. Console.Write("Stack values:"); PrintValues(myS); // Views the first element in the Stack but does not remove it. Console.WriteLine("(Peek) \t{0}", myS.Peek()); // Displays the Stack. Console.Write("Stack values:"); PrintValues(myS); Console.ReadLine(); } public static void PrintValues(IEnumerable myCollection) { foreach (Object obj in myCollection) Console.Write(" {0}", obj);

Page 79: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

79 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine(); } } }

OutPut:

About Queue?

A Queue represents a first-in, first-out collection of objects. An example of a queue is a line of people

waiting. Queue<T> is the class in the System.Collection.Generic Namespace, where T specifies the type

of elements in the queue.

Constructors:

1. Queue<T> Constructor - Initializes a new instance of the Queue<T> class that is empty. The next

lines shows how we create the empty queue.

Queue<string> queue = newQueue<string>();

2. Queue<T> Constructor (IEnumerable<T>) - Initializes a new instance of the Queue<T> class that

contains elements copied from the specified collection.

string[] courses = { "MCA","MBA", "BCA","BBA", "BTech","MTech" };

Queue<string> queue = newQueue<string>(courses);

Page 80: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

80 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

3. Queue<T> Constructor (Int32) - Initializes a new instance of the Queue<T> class that is empty

and has the specified initial capacity.

Queue<string> queue = newQueue<string>(4)

using System; using System.Collections; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //Queue is used to store non-homogeneous data types in First In First Out(FIFO) order under a common name Queue obj = new Queue(); obj.Enqueue("Madhan"); obj.Enqueue("Kumar"); obj.Enqueue("Mamidala"); foreach (var item in obj) { Console.WriteLine(item); } Console.ReadLine(); } } }

OutPut:

About difference b/w DeQueue() and Peek()?

Dequeue:

Page 81: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

81 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Dequeue means to remove something from queue. When we want to remove the value from queue

only that value which is at top is removed because as I discussed queue uses a LIFO policy. So the value

enqueue first will remove at first. To dequeue value from queue, queue class provides us a function

named dequeue (). The function takes nothing and returns object type value. When the value is

dequeue it is removed from the queue and the next value becomes the peek value.

Peek:

When we do dequeue the value at top removes form the queue. But sometimes we do not know that

what value is at top in queue and we do not want to dequeue it without knowing. So for this purpose we

have a function named peek (). The function takes nothing but it returns object value which is at peek

but does not remove that value like dequeue function.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { class Program { static void Main(string[] args) { // Creates and initializes a new Queue. Queue myQ = new Queue(); myQ.Enqueue("The"); myQ.Enqueue("quick"); myQ.Enqueue("brown"); myQ.Enqueue("fox"); // Displays the Queue. Console.Write("Queue values:"); PrintValues(myQ); // Removes an element from the Queue. Console.WriteLine("(Dequeue)\t{0}", myQ.Dequeue()); // Displays the Queue. Console.Write("Queue values:"); PrintValues(myQ); // Removes another element from the Queue.

Page 82: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

82 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine("(Dequeue)\t{0}", myQ.Dequeue()); // Displays the Queue. Console.Write("Queue values:"); PrintValues(myQ); // Views the first element in the Queue but does not remove it. Console.WriteLine("(Peek) \t{0}", myQ.Peek()); // Displays the Queue. Console.Write("Queue values:"); PrintValues(myQ); Console.ReadLine(); } public static void PrintValues(IEnumerable myCollection) { foreach (Object obj in myCollection) Console.Write(" {0}", obj); Console.WriteLine(); } } }

OutPut:

About Generic Collection Dictionary?

A dictionary, also called an associative array, is a collection of unique keys and a collection of values,

where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take

more memory, because for each value there is also a key.

Page 83: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

83 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //Dictionary is used to store specified homogeneous data types with Key and Value pairs under a common name Dictionary<int, string> Dint =new Dictionary<int, string>(); // Add some elements to the dictionary. Dint.Add(1, "Student 1"); Dint.Add(2, "Student 2"); Dint.Add(3, "Student 3"); Dint.Add(4, "Student 4"); // The Add method throws an exception if the new key is // already in the dictionary. //Dint.Add(3, "Student 5"); // The Item property is another name for the indexer, so you // can omit its name when accessing elements. Console.WriteLine("For key = \"1\", value = {0}.",Dint[1]); Console.ReadLine(); } } }

OutPut:

Page 84: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

84 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Generic Collection List?

One of the classes introduced by the System.Collections.Generics namespace is named List. This is

probably the most commonly used generic class of the .NET Framework. It is primarily

the System.Collections.Generics equivalent of the System.Collections's ArrayList. It allows you to

create a list of any kind of value.

Like any normal (non-static) class, to use a List object, you must first declare a variable for it. As a

reminder of how to use a generic class, the formula to declare the variable is:

List<TypeName>VariableName = new List<TypeName>();

You can also declare the variable using the var keyword:

var VariableName = new List<TypeName>();

You can also use the dynamic keyword:

dynamic VariableName = new List<TypeName>();

These techniques use the default constructor of the List class. If the list is made of values of primitive

types, put that value in the TypeName placeholder.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //List is used to store specified homogeneous data types under a common name List<int> lstStudentint = new List<int>(); lstStudentint.Add(1); lstStudentint.Add(2); lstStudentint.Add(3);

Page 85: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

85 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

lstStudentint.Add(4); lstStudentint.Add(5); //lstStudent.Add("Student 1"); Console.WriteLine(); foreach (int dinosaur in lstStudentint) { Console.WriteLine(dinosaur); } Console.ReadLine(); } } }

OutPut:

About Generic Collection Queue?

A Queue represents a first-in, first-out collection of objects. An example of a queue is a line of people

waiting. Queue<T> is the class in the System.Collection.Generic Namespace, where T specifies the type

of elements in the queue. In this article I explain the constructor, properties and methods of the Queue

class.

Constructors

1. Queue<T> Constructor - Initializes a new instance of the Queue<T> class that is empty. The next

lines shows how we create the empty queue.

Queue<string> queue = newQueue<string>();

2. Queue<T> Constructor (IEnumerable<T>) - Initializes a new instance of the Queue<T> class that

contains elements copied from the specified collection.

Page 86: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

86 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

string[] courses = { "MCA","MBA", "BCA","BBA", "BTech","MTech" };

Queue<string> queue = newQueue<string>(courses);

3. Queue<T> Constructor (Int32) - Initializes a new instance of the Queue<T> class that is empty

and has the specified initial capacity.

Queue<string> queue = newQueue<string>(4);

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //Queue is used to store specified homogeneous data types with FIFO order under a common name Queue<string> numbers = new Queue<string>(); numbers.Enqueue("one"); numbers.Enqueue("two"); numbers.Enqueue("three"); numbers.Enqueue("four"); numbers.Enqueue("five"); // A queue can be enumerated without disturbing its contents. foreach (string number in numbers) { Console.WriteLine(number); } Console.WriteLine("\nDequeuing '{0}'", numbers.Dequeue()); Console.WriteLine("Peek at next item to dequeue: {0}", numbers.Peek()); Console.WriteLine("Dequeuing '{0}'", numbers.Dequeue()); Console.ReadLine(); } } }

OutPut:

Page 87: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

87 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Generic Collection Stack?

A stack is a Last-In-First-Out (LIFO) data structure. The last element added to the queue will be the first

one to be removed. The C language uses a stack to store local data in a function. The stack is also used

when implementing calculators.

OutPut:

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //Stack is used to store specified homogeneous data types with FILO order under a common name ////Stack Stack<string> numbers = new Stack<string>(); numbers.Push("one");

Page 88: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

88 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

numbers.Push("two"); numbers.Push("three"); numbers.Push("four"); numbers.Push("five"); // A stack can be enumerated without disturbing its contents. foreach (string number in numbers) { Console.WriteLine(number); } Console.WriteLine("\nPopping '{0}'", numbers.Pop()); Console.WriteLine("Pop at next item to destack: {0}", numbers.Peek()); Console.WriteLine("Popping '{0}'", numbers.Pop()); Console.ReadLine(); } } }

About SortedList?

The SortedList class represents a collection of key-and-value pairs that are sorted by the keys and are

accessible by key and by index.

A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed

using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using

a key, it is a Hashtable. The collection of items is always sorted by the key value.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { ////SortedList is apply sort order for the elements automatically SortedList<int, string> Slst =new SortedList<int, string>(); //Add some elements to the dictionary. Slst.Add(1, "Student 1");

Page 89: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

89 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Slst.Add(3, "Student 3"); Slst.Add(2, "Student 2"); Slst.Add(4, "Student 4"); // The Add method throws an exception if the new key is // already in the dictionary. //Dint.Add(3, "Student 5"); foreach (KeyValuePair<int, string> kvp in Slst) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } Console.ReadLine(); } } }

OutPut:

About IEnumerable?

The IEnumerable<T> is used to iterate a read only collection. It has only one method GetEnumeartor()

which allows you to iterate the read only collection using a foreach loop. It only iterates in the forward

direction.

As it does not contain any other functions like add, remove, count etc. So you cannot add, remove

objects in IEnumerable collection. It is a read only collection and even to find the number of objects in

Page 90: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

90 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

collection, you need to iterate through entire collection. Some of the important points about

IEnumerable<T> is as follows:

It is a read only collection.

It iterates only in forward direction.

It does not support adding, removing objects on collection.

It provides enumerator to iterate collection in forward direction.

It is the base interface for any generic collection that can be enumerated using a foreach statement. To

use iteration using a foreach the generic collection must implement the IEnumerable <T> and define

GetEnumerator() method.

GetEnumerator() method is not thread safe. Enumerator reads collection by positioning itself at the first

position of the collection. You need to call MoveNext() method to read next object in collection.

When to use IEnumerable<T>

Try answering the following questions,

Working with the read only collection

Need to read the objects in forward direction only

Not concerned about thread safety

Want to iterate the collection’s objects using foreach

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { //IEnumerable //It is a read only collection. //It iterates only in forward direction. //It does not support adding, removing objects on collection. //It provides enumerator to iterate collection in forward direction.

Page 91: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

91 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

class Category { public string Name { get; set; } public int ID { get; set; } } class Program { static void Main(string[] args) { List<Category> categories = new List<Category>() { new Category(){Name="Beverages", ID=001}, new Category(){Name="Condiments", ID=002}, new Category(){Name="Vegetables", ID=003}, new Category(){Name="Grains", ID=004}, new Category(){Name="Fruit", ID=005} }; IEnumerable<Category> categories1 = categories; foreach (var item in categories1) { Console.WriteLine("{0} {1}", item.ID, item.Name); } Console.ReadLine(); } } }

OutPut:

About IQueryable?

The IQueryable is defined as below:

Page 92: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

92 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

It extends the IEnumerable, hence it allows you to iterate over collection using the foreach statement.

All the properties of IQueryable are read only.

IQueryable<T> extends IQueryable and the IEnumerable.

If you are fetching records from remote databases IQueryable<T> should be used. It constructs the

query using an Expression Tree. On the other hand in the IEnumerable <T> the query is constructed

using delegates. Both IQueryable<T> and IEnumerable <T> support lazy loading of data from remote

database servers.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { //IQueryable //If you are fetching records from remote databases IQueryable<T> should be used. It constructs the query using an Expression Tree. //When to use //Working with the queryable datasource //Need to apply filter on data at the datasource //Need to apply paging , composition //Working with external data source //Needs to load data in deferred way //Need to use foreach to iterate collection class Category { public string Name { get; set; } public int ID { get; set; } } class Program { static void Main(string[] args) { MyDataContext dc = new MyDataContext(); IQueryable<Category> list = dc.Category.Where(p => p.Name.StartsWith("S")); list = list.Take<Category>(10); foreach (var item in list) {

Page 93: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

93 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine("{0} {1}", item.ID, item.Name); } Console.ReadLine(); } } }

What's the difference between IEnumerable<T> and List<T> ?

1. IEnumerable is an interface, where as List is one specific implementation of IEnumerable. List is a class. 2. FOR-EACH loop is the only possible way to iterate through a collection of IEnumerable, where as List can be iterated using several ways. List can also be indexed by an int index, element can be added to and removed from and have items inserted at a particular index. 3. IEnumerable doesn't allow random access, where as List does allow random access using integral index. 4. In general from a performance standpoint, iterating thru IEnumerable is much faster than iterating thru a List.

About Class?

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //Class is a collection of member variables and member methods //Class contains Destructor where as struct doesn't //Class will support inheritance class Customer { //Fields public string _firstName; public string _lastName; //Property public string name { get; set; } //Constructor to initialize fields public Customer(string FirstName, string LastName) { _firstName = FirstName; _lastName = LastName; }

Page 94: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

94 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//Destructor to release objects ~Customer() { } //Method public void PrintFullName() { Console.WriteLine("Full Name : " + _firstName + " " + _lastName); } } class Program { static void Main(string[] args) { Customer cust = new Customer("Mamidala", "Madhan"); cust.PrintFullName(); Console.ReadLine(); } } }

OutPut:

About public access modifier?

The public keyword is an access modifier for types and type members. Public access is the most

permissive access level.

There are no restrictions on accessing public members.

Page 95: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

95 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Accessibility:

Can be accessed by objects of the class

Can be accessed by derived classes

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { // public-The type or member can be accessed by any other code in the same assembly or another assembly that references it. class Customer { //Fields public string _firstName; public string _lastName; //Property public string name { get; set; } //Constructor to initialize fields public Customer(string FirstName, string LastName) { _firstName = FirstName; _lastName = LastName; } //Destructor to release objects ~Customer() { } //Method public void PrintFullName() { Console.WriteLine("Full Name : " + _firstName + " " + _lastName); } } class Program { static void Main(string[] args) { Customer cust = new Customer("Mamidala", "Madhan"); cust.PrintFullName();

Page 96: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

96 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.ReadLine(); } } }

OutPut:

About private Access Modifier?

The private keyword is a member access modifier. Private access is the least permissive access level.

Private members are accessible only within the body of the class or the struct in which they are

declared.

Nested types in the same body can also access those private members.

It is a compile-time error to reference a private member outside the class or the struct in which

it is declared.

For a comparison of private with the other access modifiers

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //private:The type or member can be accessed only by code in the same class or struct. class Customer { //Fields private string _firstName; private string _lastName;

Page 97: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

97 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//Constructor to initialize fields public Customer(string FirstName, string LastName) { _firstName = FirstName; _lastName = LastName; } private void PrintFullName() { Console.WriteLine("Full Name : " + _firstName + " " + _lastName); } } class Program { static void Main(string[] args) { Customer cust = new Customer("Mamidala", "Madhan"); //Which is not accessible out side of the class //cust.PrintFullName(); Console.ReadLine(); } } }

OutPut:

About protected Access Modifier?

Protected is an accessibility keyword. The protected modifier is between the private and public

domains. It is the same as private but allows derived classes to access the member.

Page 98: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

98 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Example. This program introduces two classes, A and B. B is derived from A. Class A has two fields, a

protected int and a private int. In class B, we can access the protected int, but not the private int.Int

Note: The accessibility domain of protected fields includes all derived classes. This is a key difference.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { ////protected:The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class. class Customer { //Fields protected string _firstName; protected string _lastName; public Customer() { } //Constructor to initialize fields public Customer(string FirstName, string LastName) { _firstName = FirstName; _lastName = LastName; } protected void PrintFullName() { Console.WriteLine("Full Name : " + _firstName + " " + _lastName); } } class CustomerDerived : Customer { public CustomerDerived(string FirstName, string LastName) { _firstName = FirstName; _lastName = LastName; } public void TestPrint() { //protected member which is accessible by derived class PrintFullName();

Page 99: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

99 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} } class Program { static void Main(string[] args) { CustomerDerived cust = new CustomerDerived("Madhan","Mamidala"); cust.TestPrint(); Console.ReadLine(); } } }

OutPut:

About properties?

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.

Properties do not name the storage locations. Instead, they have accessors that read, write, or

compute their values.

For example, let us have a class named Student, with private fields for age, name, and code. We

cannot directly access these fields from outside the class scope, but we can have properties for

accessing these private fields.

Page 100: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

100 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Accessors

The accessor of a property contains the executable statements that helps in getting (reading or

computing) or setting (writing) the property. The accessor declarations can contain a get

accessor, a set accessor

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //Properties //Properties provides ability to validate user input values to class members //Properties provide ability to make class members as readonly class Student { //public int ID; //public string Name; //public int Passmark=35; private int _id; private string _name; private int _passmark = 35; public int Id { set { if (value <= 0) { throw new Exception("ID not to be negative"); } _id = value; } get { return _id; } } public string Name { set { _name = value; } get { return _name;

Page 101: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

101 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} } public int Passmark { //set //{ // _passmark = value; //} get { return _passmark; } } //Auto implemented properties(C# compiler automatically create private fields automatically) public int City { set; get; } } class Program { static void Main(string[] args) { //Properties Student c = new Student(); c.Id = -101;//we can validate the user input using properties c.Name = "Madhan"; c.Passmark = 0;//we can make class members as readonly Console.ReadLine(); } } }

OutPut:

Page 102: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

102 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About default constructor?

Classes have default constructors. These constructors are injected into all class declarations that do not

introduce other constructors. The default constructor provides a simpler syntax for type definitions. It is

an important detail.You can call the default constructor anywhere. It is a public parameterless instance

constructor.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //Constructor //Constructor is a special type of method,which has same name of class name and used to initialze the class variables //Every class by default have one constructor which ic=s called as default constructor class Student { string Name; string Address; public Student() { Name = "Madhan"; Address = "India"; } public void Print() { Console.WriteLine("Name is {0} and Address is {1}", Name, Address); } } class Program { static void Main(string[] args) { //Default constructor Student c = new Student(); c.Print(); Console.ReadLine(); }

Page 103: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

103 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} }

OutPut:

About parameter Constructor?

1. A constructor with parameters is called parameterized Constructor.

2. A Class or Struct can have multiple parameterized constructors as long as they have different

method signature. They follow the same concept of method overloading.

3. Compiler provides Default Constructors only if there is no constructor (Default or

Parameterized) defined in a class.

4. Parameterized Constructors can exist even without the existence of Default Constructors.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //Constructor //parameter Constructor is used to pass values for class members dynamically class Student { string Name; string Address; public Student(string _Name,string _Address) { Name = _Name; Address = _Address; } public void Print() {

Page 104: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

104 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine("Name is {0} and Address is {1}", Name, Address); } } class Program { static void Main(string[] args) { //Parameter constructor Student c = new Student("Madhan","India"); c.Print(); Console.ReadLine(); } } }

OutPut:

About static constructor?

1. To initialize a Static Class or Static variables in Non-Static Class, Static Constructors are used

2. Access Modifiers are not allowed on Static Constructors

3. Static Constructors cannot be parameterized

4. There can be only one Static Constructors per class

5. Static Constructors cannot have an explicit 'this' or 'base' constructor call, i.e., Static

Constructors cannot be called directly

6. Static Constructors are called automatically before the first instance of a class is created or any

static member is referenced

7. Static Constructors are called only once in the lifetime of a class

Page 105: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

105 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //Constructor //static Constructor calls only one time when first object creation //where as normal constructor calls every time when new object create for the class class StaticConstructor { //public int a; //static public int b; public StaticConstructor() { Console.WriteLine("In Instance Constructor"); } static StaticConstructor() { Console.WriteLine("In Static Constructor"); } } class Program { static void Main(string[] args) { //static constructor StaticConstructor c1 = new StaticConstructor(); StaticConstructor c2 = new StaticConstructor(); Console.ReadLine(); } } }

OutPut:

Page 106: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

106 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About copy constructor?

A parameterized constructor that contains a parameter of same class type is called as copy constructor.

Main purpose of copy constructor is to initialize new instance to the values of an existing instance.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //Constructor //copy Constructor accepts object as a parameter class CopyConstructor { //public int a; //static public int b; int A, B; public CopyConstructor(int X, int Y) { A = X; B = Y; } //Copy Constructor public CopyConstructor(CopyConstructor T) { A = T.A; B = T.B; } public void Print() { Console.WriteLine("A = {0}\tB = {1}", A, B); } } class Program

Page 107: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

107 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{ static void Main(string[] args) { CopyConstructor c1 = new CopyConstructor(10, 20); CopyConstructor c2 = new CopyConstructor(c1); c1.Print(); c2.Print(); Console.ReadLine(); } } }

OutPut:

About private constructor?

1. A constructor becomes a private constructor when we declare with private access specifier.

2. Private Constructors can neither be instantiated nor inherited from other class.

3. Object of class can only be created in the class itself.

4. Microsoft recommends its uses to implement Singleton Pattern.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //Constructor //private Constructor oppose to create object for a class class PrivateConstructor

Page 108: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

108 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{ static public int b = 10; static public int c = 20; private PrivateConstructor() { } } class Program { static void Main(string[] args) { //object creation of a class which contains private constructor gives an error //PrivateConstructor c1 = new PrivateConstructor(); PrivateConstructor.b = 50; PrivateConstructor.c = 60; Console.WriteLine("b value {0} c value {1}", PrivateConstructor.b, PrivateConstructor.c); Console.ReadLine(); } } }

OutPut:

About static class?

Page 109: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

109 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

A static class is basically the same as a non-static class, but there is one difference: a static class cannot

be instantiated. In other words, you cannot use the new keyword to create a variable of the class type.

Because there is no instance variable, you access the members of a static class by using the class name

itself.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { // ////Static Class (For Static class we can't create instance) static class Customer { //Fields static string _firstName; static string _lastName; // (Default Constructor) static Customer() { _firstName = "Madhan"; _lastName = "Mamidala"; } static public void PrintFullName() { Console.WriteLine("Full Name : " + _firstName + " " + _lastName); Console.ReadLine(); } } class Program { static void Main(string[] args) { ////Static Class Customer.PrintFullName(); Console.ReadLine(); } } }

OutPut:

Page 110: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

110 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About abstract class?

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.

Features:

1. An abstract calss can inherit from a class and one or more interfaces.

2. An abstract class can implement code with non-Abstract methods.

3. An Abstract class can have modifiers for methods, properties etc.

4. An Abstract class can have constants and fields.

5. An abstract class can implement a property.

6. An abstract class can have constructors or destructors.

7. An abstract class cannot be inherited from by structures.

8. An abstract class cannot support multiple inheritance.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //////Abstract Class (For Abstract class also we can't create instance) //abstract class will contains instance methods as well as abstract methods(a method which contains signature but not defination /implementation called as Abstract method) abstract class Customer { //Fields public string _firstName; public string _lastName;

Page 111: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

111 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

// (Default Constructor) public Customer() { _firstName = "Madhan"; _lastName = "Mamidala"; } public abstract void PrintFullName(); } class DerivedCustomer:Customer { public override void PrintFullName() { Console.WriteLine("First name is {0} Last Name is {1}",base._firstName,base._lastName); } } class Program { static void Main(string[] args) { ////abstarct Class doesn't support object creation //Customer c = new Customer(); DerivedCustomer d = new DerivedCustomer(); d.PrintFullName(); Console.ReadLine(); } } }

OutPut:

About interface?

Page 112: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

112 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

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.

Interfaces define properties, methods, and events, which are the members of the interface.

Interfaces contain only the declaration of the members. It is the responsibility of the deriving

class to define the members. It often helps in providing a standard structure that the deriving

classes would follow.

Abstract classes to some extent serve the same purpose, however, they are mostly used when

only few methods are to be declared by the base class and the deriving class implements the

functionalities.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //interface can contains only abstarct methods //interface can contains properties interface ICustomer { //properties string Name { get; set; } string Address { get; set; } //publich and abstarct methods(but no need to mention them as public and abstract) void PrintName(); void PrintAddress(); } class Customer:ICustomer { //implemeting properties of a interface private string name; public string Name { get { return name; }

Page 113: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

113 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

set { name = value; } } private string address; public string Address { get { return address; } set { address = value; } } //implementing methods of a interface public void PrintName() { Console.WriteLine("Name : {0}", Name); } public void PrintAddress() { Console.WriteLine("Address : {0}", Address); } } class Program { static void Main(string[] args) { Customer d = new Customer(); d.Name = "Madhan"; d.Address = "India"; d.PrintName(); d.PrintAddress(); Console.ReadLine(); } } }

OutPut:

Page 114: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

114 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About partial class?

There are several situations when splitting a class definition is desirable:

When working on large projects, spreading a class over separate files enables multiple

programmers to work on it at the same time.

When working with automatically generated source, code can be added to the class

without having to recreate the source file. Visual Studio uses this approach when it

creates Windows Forms, Web service wrapper code, and so on. You can create code

that uses these classes without having to modify the file created by Visual Studio.

To split a class definition, use the partial keyword modifier

The partial keyword indicates that other parts of the class, struct, or interface can be

defined in the namespace. All the parts must use the partial keyword. All the parts must

be available at compile time to form the final type. All the parts must have the same

accessibility, such as public, private, and so on.

If any part is declared abstract, then the whole type is considered abstract. If any part is

declared sealed, then the whole type is considered sealed. If any part declares a base

type, then the whole type inherits that class.

All the parts that specify a base class must agree, but parts that omit a base class still

inherit the base type. Parts can specify different base interfaces, and the final type

implements all the interfaces listed by all the partial declarations. Any class, struct, or

interface members declared in a partial definition are available to all the other parts.

The final type is the combination of all the parts at compile time.

Page 115: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

115 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //////Partial Class (Spilt the functionality in to two or more classes) partial class Customer { //Fields public string _firstName; public string _lastName; // (Default Constructor) public Customer() { _firstName = "Madhan"; _lastName = "Mamidala"; } public void PrintFirstName() { Console.WriteLine("First Name : {0}", _firstName); } } partial class Customer { public void PrintLastName() { Console.WriteLine("Last Name : {0}", _lastName); } } class Program { static void Main(string[] args) { Customer d = new Customer(); //runtime compiler clubs all the methods in to single class d.PrintFirstName(); d.PrintLastName(); Console.ReadLine();

Page 116: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

116 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} } }

OutPut:

About Data Abstraction and Encapsulation?

Abstraction

Abstraction allows us to represent complex real world in simplest manner. It is process of identifying the

relevant qualities and behaviors an object should possess, in other word represent the necessary feature

without representing the back ground details. Abstraction is a process of hiding work style of an object

and showing only those information which are required to understand the object. Abstraction means

putting all the variables and methods in a class which are necessary.

Encapsulation

It is a process of hiding all the internal details of an object from the outside real world. The word

Encapsulation, like Enclosing into the capsule. It restrict client from seeing its internal view where

behavior of the abstraction is implemented. In Encapsulation, generally to hide data making it private

and expose public property to access those data from outer world. Encapsulation is a method for

protecting data from unwanted access or alteration. Encapsulation is the mechanism by which

Abstraction is implemented.

Difference between Abstraction and Encapsulation

Abstraction is a process. It is the act of identifying the relevant qualities and behaviors an object should possess.

Encapsulation is the mechanism by which the abstraction is implemented.

Page 117: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

117 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Abstraction Encapsulation

Abstraction solves the problem in the design

level. Encapsulation solves the problem in the implementation level.

Abstraction is used for hiding the unwanted

data and giving only relevant data.

Encapsulation is hiding the code and data into a single unit to protect

the data from outer world.

Abstraction is set focus on the object instead of

how it does it.

Encapsulation means hiding the internal details or mechanics of how

an object does something.

Abstraction is outer layout in terms of design.

For Example: - Outer Look of a iPhone, like it

has a display screen.

Encapsulation is inner layout in terms of implementation.

For Example: - Inner Implementation detail of a iPhone, how Display

Screen are connect with each other using circuits

In the following program in order to calculate the Division of 2 numbers user needs to call two methods

which are Validate() and Calculate() ,which is complex to the end user.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { ////Data Abstraction(Providing only necessary details to the user) and Data Encapsulation(Hiding the complxity to the user) class DivideFunction { public int FirstNumber; public int SecondNumber; public DivideFunction(int firstNumber, int secondNumber) { FirstNumber = firstNumber; SecondNumber = secondNumber; } public void Validate() { if (SecondNumber == 0) { throw new Exception("Divident must not be zero"); } } public double Calculate() {

Page 118: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

118 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

return FirstNumber / SecondNumber; } } class Program { static void Main(string[] args) { //Data Absraction and Data Encapsulation DivideFunction d = new DivideFunction(10, 5); try { //inorder to calculate Division user needs to call Validate() and Calculate() d.Validate(); double dd = d.Calculate(); Console.WriteLine(dd); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } } }

To reduce the complexity to the end user we are calling Validate() in Calculate() method itself, so end

user can use Calculate() to get Division of two numbers.

The process of reducing the complexity to the end user is called as Encapsulation.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { ////Data Abstraction(Providing only necessary details to the user) and Data Encapsulation(Hiding the complxity to the user) class DivideFunction { public int FirstNumber; public int SecondNumber; public DivideFunction(int firstNumber, int secondNumber)

Page 119: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

119 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{ FirstNumber = firstNumber; SecondNumber = secondNumber; } public void Validate() { if (SecondNumber == 0) { throw new Exception("Divident must not be zero"); } } public double Calculate() { Validate(); return FirstNumber / SecondNumber; } } class Program { static void Main(string[] args) { //Data Absraction and Data Encapsulation DivideFunction d = new DivideFunction(10, 5); try { //inorder to calculate Division,now user needs to call Calculate() method only //Reducing the complexity to the end user is called as Encapsulation. double dd = d.Calculate(); Console.WriteLine(dd); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } } }

But still user can call the Validate() method as it is public method, lets hide Validate() by making it as

private so user can’t see the Validate().

Page 120: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

120 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The process of hiding unnecessary data to the end user is called as Data Abstarction. Here we are hiding

the Validate() method to the end user.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { ////Data Abstraction(Providing only necessary details to the user) and Data Encapsulation(Hiding the complxity to the user) class DivideFunction { public int FirstNumber; public int SecondNumber; public DivideFunction(int firstNumber, int secondNumber) { FirstNumber = firstNumber; SecondNumber = secondNumber; } //Hiding the Validate() method by mentioning it as private,this process is calles as Data Abstraction private void Validate() { if (SecondNumber == 0) { throw new Exception("Divident must not be zero"); } } public double Calculate() { Validate(); return FirstNumber / SecondNumber; } } class Program { static void Main(string[] args) { //Data Absraction and Data Encapsulation DivideFunction d = new DivideFunction(10, 5); try { //inorder to calculate Division,now user needs to call Calculate() method only //Reducing the complexity to the end user is called as Encapsulation.

Page 121: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

121 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

double dd = d.Calculate(); Console.WriteLine(dd); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } } }

About Method Overloading?

The process of creating more than one method in a class with same name or creating a method in

derived class with same name as a method in base class is called as method overloading.

While overloading methods, a rule to follow is the overloaded methods must differ either in number of

arguments they take or the data type of at least one argument.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //Method Overloading //One ore more methods in same class with same name and same Method signature,is called as Method Overloading //Method oveloading doesn't include return type Program p = new Program(); p.Add(5, 10); p.Add(5, 10, 15); Console.ReadLine(); } //Method Overloading public void Add(int a, int b)

Page 122: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

122 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{ Console.WriteLine(a + b); } public void Add(int a, int b, int c) { Console.WriteLine(a + b + c); } } }

OutPut:

About Operator Overloading?

Operator. Overloaded operators sometimes improve program syntax. With the operator keyword,

public static operator methods used by the compiler when the designated operators are encountered.

This sometimes makes programs and frameworks clearer.

Example. This program declares a Widget class. Here, Widgets can be added together or incremented

with the same syntax used for integers. In the Widget class, we provide two public static methods:

operator +, and operator ++.

These two methods return an instance of Widget. They receive two or one formal parameters

depending on whether the operator is binary (+) or unary (++). They are overloaded operator

implementations.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //Operator Overloading

Page 123: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

123 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//Overloading operators to work with objects is called as operator overloading class Box { private double length; // Length of a box private double breadth; // Breadth of a box private double height; // Height of a box public Box() { } public Box(double _length, double _breadth, double _height) { length = _length; breadth = _breadth; height = _height; } public double getVolume() { return length * breadth * height; } //// Overload + operator to add two Box objects. public static Box operator +(Box b, Box c) { Box box = new Box(); box.length = b.length + c.length; box.breadth = b.breadth + c.breadth; box.height = b.height + c.height; return box; } } class Program { static void Main(string[] args) { //Method Overloading //////Operator Overloading Box Box1 = new Box(10, 20, 30); // Declare Box1 of type Box Box Box2 = new Box(40, 50, 60); // Declare Box2 of type Box Box Box3 = new Box(); // Declare Box3 of type Box double volume = 0.0; // Add two object as follows: //Here we are overloading + operator to add two objects Box3 = Box1 + Box2; // volume of box 3

Page 124: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

124 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

volume = Box3.getVolume(); Console.WriteLine("Volume of Box3 : {0}", volume); Console.ReadLine(); Console.ReadLine(); } } }

OutPut:

About Method Overriding?

Creating a method in derived class with same signature as a method in base class is called as method

overriding.

Same signature means methods must have same name, same number of arguments and same type of

arguments.

Method overriding is possible only in derived classes, but not within the same class.

When derived class needs a method with same signature as in base class, but wants to execute different

code than provided by base class then method overriding will be used.

To allow the derived class to override a method of the base class, C# provides two options, virtual

methods and abstract methods.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { ////Method Overriding //Same method signature in both base and derived class is called as Method Overriding class Employee { public virtual void GetSalary()

Page 125: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

125 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{ Console.WriteLine("Employee Salary"); } } class ParminentEmployee:Employee { public override void GetSalary() { Console.WriteLine("Perminent Employee Salary"); } } class Program { static void Main(string[] args) { //////Method Overriding ParminentEmployee p = new ParminentEmployee(); p.GetSalary(); Console.ReadLine(); } } }

OutPut:

About Inheritance?

Acquiring (taking) the properties of one class into another class is called inheritance. Inheritance

provides reusability by allowing us to extend an existing class.

The reason behind OOP programming is to promote the reusability of code and to reduce complexity in

code and it is possible by using inheritance.

The following are the types of inheritance in C#.

Page 126: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

126 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The inheritance concept is based on a base class and derived class. Let us see the definition of a base

and derived class.

Base class: is the class from which features are to be inherited into another class.

Derived class: it is the class in which the base class features are inherited.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //Inheritance:The process of deriving new class by using existing class is called as inheritance //Code Reusability is main Advantage of inheritance //Why Inheritance class FullTimeEmployee { string fname; string lname; string email; string yearlysalary; } class PartTimeEmployee { string fname; string lname; string email; string hourlysalary; } //Common code vailable for FT and PT employees so we can build common Class Employye and //Move all the common code to Employee class and reuse those fields when required. class Employee { public string fname;

Page 127: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

127 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

public string lname; public string email; } class FullTimeEmployee:Employee { public double yearlysalary; public void PrintFullName() { Console.WriteLine("Full Name:"+fname+" "+lname); } } class PartTimeEmployee : Employee { public double hourlysalary; } class Program { static void Main(string[] args) { //////Inheritance FullTimeEmployee fte = new FullTimeEmployee(); fte.fname = "Madhan"; fte.lname = "Mamidala"; fte.email = "[email protected]"; fte.yearlysalary = 1000000; fte.PrintFullName(); Console.ReadLine(); } } }

OutPut:

Page 128: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

128 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About single inheritance?

Single Inheritance means when a single base is been implemented to single derived class is called as

Single Inheritance.Means we have only one parent class and one child class.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //Single Inheritance:The process of deriving new class by using one existing class is called as single inheritance. class Employee { public string fname; public string lname; public string email; } class FullTimeEmployee:Employee { public double yearlysalary; public void PrintFullName() { Console.WriteLine("Full Name:"+fname+" "+lname); } }

Page 129: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

129 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

class Program { static void Main(string[] args) { //////Single Inheritance FullTimeEmployee fte = new FullTimeEmployee(); fte.fname = "Madhan"; fte.lname = "Mamidala"; fte.email = "[email protected]"; fte.yearlysalary = 1000000; fte.PrintFullName(); Console.ReadLine(); } } }

OutPut:

About multi-level inheritance?

When a derived class is created from another derived class or let me put it in this way that a class is

created by using another derived class and this type of implementation is called as multilevel

Inheritance

Page 130: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

130 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //// Multi level Inheritance:The process of deriving a new class by already derived class is called as multi-level inheritance class Employee { public string fname; public string lname; public string email; } class FullTimeEmployee : Employee { public string NatureOfWork; public double yearlysalary; public void PrintFullName() { Console.WriteLine("Full Name:" + fname + " " + lname); } } class EmployeeOfTheYear : FullTimeEmployee { public string achievements; public void EmployeeAchievements() { Console.WriteLine("Full Name:" + fname + " " + lname + " " + achievements); }

Page 131: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

131 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} class Program { static void Main(string[] args) { //////Multilevel Inheritance EmployeeOfTheYear fte = new EmployeeOfTheYear(); fte.fname = "Madhan"; fte.lname = "Mamidala"; fte.email = "[email protected]"; fte.yearlysalary = 1000000; fte.NatureOfWork = "Developer"; fte.achievements = "Completed all task in time"; fte.EmployeeAchievements(); Console.ReadLine(); } } }

OutPut:

About multiple inheritance?

Due to the complexity of a code multiple inheritance is not been supported in C# or in DOT.NET but

DOT.NET or C# supports multiple interfaces.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { ////// Multiple Inheritance:The process of deriving new class by more than one base classes is called as multiple inheritance //C# doesn't support multiple inheritance //The reason for that is,if more than one base class having same method or property or filed name C# compiler will get ambiguity //to make call of the methods or properties or fileds.

Page 132: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

132 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//This problem is called as dimond problem //Following is the example to explain the issue with classes of multiple inheritance public class class1 { public void Add() { Console.WriteLine("Class 1 Add method"); } } public class class2 { public void Add() { Console.WriteLine("Class 2 Add method"); } } public class MyDerivedClass : class1, class2 { } class Program { static void Main(string[] args) { //////Multilevel Inheritance MyDerivedClass d = new MyDerivedClass(); //Here compiler get ambiguity to call Add() method,whether it needs to call from class1 or class2 //So to avaoid this complexity microsoft decided not to support multiple inheritance in C#. //d.Add(); Console.ReadLine(); } } }

OutPut:

Page 133: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

133 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About multiple inheritance through interfaces?

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { ////// Multiple Inheritance throught the interfaces public interface Interface1 { void Add(); } public interface Interface2 { void Add(); } public class MyDerivedClass : Interface1, Interface2 { void Interface1.Add() { Console.WriteLine("You are in interface1 Add method"); } void Interface2.Add() { Console.WriteLine("You are in interface2 Add method"); } } class Program { static void Main(string[] args) { ////Multiple Inheritance MyDerivedClass myclass = new MyDerivedClass(); //Here with explicit interface method call we can tell the compiler to call Add() from iterface1 and intterface2 ((Interface1)myclass).Add(); ((Interface2)myclass).Add(); Console.ReadLine(); } } }

OutPut:

Page 134: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

134 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About multiple interface with one class and one interface?

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //// Multiple Inheritance 1 class and 1 interface public class class1 { public void Add() { Console.WriteLine("You are in class1 Add method"); } } public interface Interface2 { void Add(); } public class MyDerivedClass : class1, Interface2 { void Interface2.Add() { Console.WriteLine("You are in interface2 Add method"); } } class Program { static void Main(string[] args) { //////Multiple Inheritance with 1 class and 1 Interface MyDerivedClass myclass = new MyDerivedClass(); myclass.Add(); ((Interface2)myclass).Add(); Console.ReadLine(); }

Page 135: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

135 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} }

OutPut:

About Extension Method?

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //////Extension Methods:An extension method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types. //We can say that it extends the functionality of an existing type in .NET. public static class MyMathExtension { public static int factorial(this int x) { if (x <= 1) return 1; if (x == 2) return 2; else return x * factorial(x - 1); } } class Program { static void Main(string[] args) { //////Extension Methods int x = 3; Console.WriteLine(x.factorial()); Console.ReadLine(); } } }

OutPut:

Page 136: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

136 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About indexers?

Indexers enable objects to be indexed in a similar manner to arrays.

A get accessor returns a value. A set accessor assigns a value.

The this keyword is used to define the indexers.

The value keyword is used to define the value being assigned by the set indexer.

Indexers do not have to be indexed by an integer value; it is up to you how to define the specific

look-up mechanism.

Indexers can be overloaded.

Indexers can have more than one formal parameter, for example, when accessing a two-

dimensional array.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { //// Indexers:Helps us to access objects as an array elements. class ParentClass { private string[] range = new string[5]; public string this[int indexrange] { get { return range[indexrange]; } set { range[indexrange] = value; }

Page 137: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

137 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} } class Program { static void Main(string[] args) { ////Indexers ParentClass obj = new ParentClass(); obj[0] = "ONE"; obj[1] = "TWO"; obj[2] = "THREE"; obj[3] = "FOUR "; obj[4] = "FIVE"; Console.WriteLine("{0}\n,{1}\n,{2}\n,{3}\n,{4}\n", obj[0], obj[1], obj[2], obj[3], obj[4]); Console.ReadLine(); } } }

OutPut:

About Generic Methods?

Generic methods have type parameters. They provide a way to parameterize the types used in a

method. This means you can provide only one implementation and call it with different types. Generic

methods require an unusual syntax form.Generic Class

Note:The syntax form for the declaration uses the <T> characters after the method name but before the

formal parameter list.

Page 138: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

138 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Example. This program demonstrates the use of a generic method in the C# language. Generic methods

use at least one explicit type parameter, which is customarily the type T or V or TValue or similar.

General way of implementing Add() method with 2 integers and 2 double data types,

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { ////Normal way of calling Add method with 2 integer parameters Add(10, 20); ////Normal way of calling Add method with 2 integer parameters Add(10.10, 20.20); Console.ReadLine(); } ////Normal way of implemetiong Add method to add 2 integer variables public static void Add(int a,int b) { Console.WriteLine("Sum of 2 interger numbers is {0}",a+b); } ////Normal way of implemetiong Add method to add 2 double point variables public static void Add(double a, double b) { Console.WriteLine("Sum is 2 floating point numbers is {0}", a + b); } } }

OutPut:

Page 139: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

139 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Implement general Add() method to handle both integer and double or any other data types.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { ////Add method with object data type Add(10, 20); Add(10.10, 20.20); Console.ReadLine(); } //By using an object type we can implement generic method which can accept any kind of data type value to get addition of 2 numbers //But problem with this approach is, every time when calling the method Boxing happing here means value type needs to convert to reference type //which is object type public static void Add(object a,object b) { Console.WriteLine("Sum is {0}", (dynamic)a + (dynamic)b); } } }

OutPut:

To avoid Boxing overhead Microsoft, provide Generic Method functionality.

using System;

Page 140: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

140 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { ////Generic Methods Add(10, 20); Add(10.10, 20.20); //or Add<int>(10, 20); Add<double>(10.10, 20.20); Console.ReadLine(); } //to avoid this problem Microsoft provided generic method which is type safe and eliminate the boxing overhead. public static void Add<T>(T a, T b) { Console.WriteLine("Sum is {0}", (dynamic)a + (dynamic)b); } } }

OutPut:

About Generic Classes?

Generic classes have type parameters. Separate classes, each with a different field type in them, can be

replaced with a single generic class. The generic class introduces a type parameter. This becomes part of

the class definition itself.Type

Page 141: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

141 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Example. One amazing feature in the C# language is the ability to specify and use generic types. These

types themselves contain type parameters, which influence the compilation of the code to use any type

you specify.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { ////Generic Classes //Where all methods in that class have generic methods. //List is a good example for generic class MyClass<int>.Add(10, 20); MyClass<double>.Add(10.10, 20.20); Console.ReadLine(); } //Generic Class class MyClass<T> { public static void Add(T a, T b) { Console.WriteLine("Sum is {0}", (dynamic)a + (dynamic)b); } public static void Sub(T a, T b) { Console.WriteLine("Sum is {0}", (dynamic)a + (dynamic)b); } public static void Mul(T a, T b) { Console.WriteLine("Sum is {0}", (dynamic)a + (dynamic)b); } } } }

OutPut:

Page 142: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

142 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Exception Handling?

An exception is a problem that arises during the execution of a program. A C# exception is a response to

an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C# exception

handling is built upon four keywords: try, catch, finally, and throw.

try: A try block identifies a block of code for which particular exceptions is activated. It is

followed by one or more catch blocks.

catch: A program catches an exception with an exception handler at the place in a program

where you want to handle the problem. The catch keyword indicates the catching of an

exception.

finally: The finally block is used to execute a given set of statements, whether an exception is

thrown or not thrown. For example, if you open a file, it must be closed whether an exception is

raised or not.

throw: A program throws an exception when a problem shows up. This is done using a throw

keyword.

To handle runtime exception, we are using exception handling, try is the block where we write code

implementation, if runtime exception occur it will go to type of catch block and execute catch block.

finally block will execute always even exception occur or not and help us to release unused objects from

memory.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook {

Page 143: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

143 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

class Program { static void Main(string[] args) { try { Console.WriteLine("Enter value for A"); byte a = Convert.ToByte(Console.ReadLine()); Console.WriteLine("Enter value for B"); byte b = Convert.ToByte(Console.ReadLine()); int c = a / b; Console.WriteLine("Division is {0}", c); } catch (DivideByZeroException ex) { Console.WriteLine("Hey man,don't provide zero value for denominator"); } catch (FormatException ex) { Console.WriteLine("Hey man,Please enter only numbers for Division operation"); } catch (OverflowException ex) { Console.WriteLine("Hey man,Please enter only numbers in between range of 0 to 255 for Division operation"); } catch (Exception ex) { Console.WriteLine("Something went wrong please conatct admin"); } finally { }

Page 144: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

144 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} } }

OutPut:

About dynamic, object and var keywords?

1.When were they introduced

var was introduced in C# 3.0

dynamic was introduced in C# 4.0

2. Type inference of variables

var is a statically typed variable. It results in a strongly typed variable, in other words the

data type of these variables are inferred at compile time. This is done based on the type

of value that these variables are initialized with.

dynamic are dynamically typed variables. This means, their type is inferred at run-time

and not the compile time in contrast to var type.

3. Initialization of variables

Page 145: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

145 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

var type of variables are required to be initialized at the time of declaration or else they

encounter the compile time error: Implicitly-typed local variables must be initialized.

dynamic type variables need not be initialized when declared.

4. Changing type of value assigned

var does not allow the type of value assigned to be changed after it is assigned to. This

means that if we assign an integer value to a var then we cannot assign a string value to

it. This is because, on assigning the integer value, it will be treated as an integer type

thereafter. So thereafter no other type of value cannot be assigned.

using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KnackHook { class Program { static void Main(string[] args) { //1.Object was introduced with C# 1.0 //1.Var was introduced with C# 3.0 //1.Dynamic was introduced with C# 4.0 //2.object can store any kind of value, because object is the base class of all type in .NET framework. //2.var can store any type of value but It is mandatory to initialize var types at the time of declaration. //2.dynamic can store any type of the variable, similar to old VB language variable. object val1; var val2 = 9;//if we omit to assign a value to var type ,it will give an error. dynamic val3; //3.Compiler has little information about the object type. . //3.var is type safe i.e. Compiler has all information about the stored value, so that it doesn't cause any issue at run-time. //3.dynamic is not type safe i.e. Compiler doesn't have any information about the type of variable.

Page 146: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

146 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

object val4; var val5 = "KnackHook"; Console.WriteLine(val5.Length);//if there is any issue it will show compile time error Console.WriteLine(val5.Increment);//See string doesn't contains method called Increment so var gives compile time error dynamic val6 = "C#"; Console.WriteLine(val6.Length);//if there is any issue all will be shown at runtime. Console.WriteLine(val6.Increment);//See string doesn't contains method called Increment but dynamic not gives compile time error,this will give error at runtime //4.Object type can be passed as method argument and method also can return object type. //4.Var type cannot be passed as method argument and method cannot return object type. Var type work in the scope where it defined. //4.Dynamic type can be passed as method argument and method also can return dynamic type. Program p = new Program(); p.Add(10, 20); p.Sub(10, 20); } public object Add(object a, object b) { return (int)a +(int) b; } public dynamic Sub(dynamic a, dynamic b) { return (int)a - (int)b; } ////var is not support here //public var Sub(var a, var b) //{ // return (int)a - (int)b; //} } }

OutPut:

Page 147: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

147 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About LINQ with selection?

Select applies a method to every element. It is an elegant way to mutate the elements in a collection

such as an array. This method receives as a parameter an anonymous function—typically specified as a

lambda expression or delegate.

Example. Let's look at a program where the Select extension method is applied to a string array. A local

variable of array type is allocated and three string literals are used. We use Select on this array

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = from n in numbers select n; Console.WriteLine("Numbers are:"); foreach (var x in lowNums) { Console.WriteLine(x); } Console.ReadLine(); } }

Page 148: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

148 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

}

OutPut:

LINQ with where condition?

The where clause is used in a query expression to specify which elements from the data source will be

returned in the query expression. It applies a Boolean condition (predicate) to each source element

(referenced by the range variable) and returns those for which the specified condition is true. A single

query expression may contain multiple where clauses and a single clause may contain multiple predicate

subexpressions.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { //With Where condition int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = from n in numbers where n < 5 select n; Console.WriteLine("Numbers <5:"); foreach (var x in lowNums) {

Page 149: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

149 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine(x); } Console.ReadLine(); } } }

OutPut:

LINQ with select many?

Select and SelectMany are projection operators. Select operator is used to select value from a collection

and SelectMany operator is used to select values from a collection of collection i.e. nested collection.

Select operator produce one result value for every source value while SelectMany produce a single

result that contains a concatenated value for every source value. Actually, SelectMany operator flatten

IEnumerable<IEnumerable<T>> to IEnumrable<T> i.e. list of list to list.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) {

Page 150: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

150 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//SelectMany - Compound from 1 int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var pairs = from a in numbersA from b in numbersB where a < b select new { a, b }; Console.WriteLine("Pairs where a < b:"); foreach (var pair in pairs) { Console.WriteLine("{0} is less than {1}", pair.a, pair.b); } Console.ReadLine(); } } }

OutPut:

LINQ with Take?

Take returns the first specified number of elements. It acts upon an IEnumerable sequence. It returns

another IEnumerable sequence containing the specified elements. We see basic usages of this extension

method.Extension Method

Page 151: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

151 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Example. Here we use the Take extension method in the C# language. Take is a method in the

System.Linq namespace that allows you to get the first several elements from a sequence. It receives an

element count.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { //Take - Simple int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var first3Numbers = numbers.Take(3); Console.WriteLine("First 3 numbers:"); foreach (var n in first3Numbers) { Console.WriteLine(n); } Console.ReadLine(); } } }

OutPut:

LINQ with TakeWhile?

Page 152: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

152 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

TakeWhile. TakeWhile returns elements while a Predicate matches. The Predicate returns true or false.

When it returns false, TakeWhile returns. TakeWhile operates from the beginning of an IEnumerable

collection.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { //TakeWhile - Simple int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6); Console.WriteLine("First numbers less than 6:"); foreach (var n in firstNumbersLessThan6) { Console.WriteLine(n); } Console.ReadLine(); } } }

OutPut:

LINQ with Skip?

Page 153: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

153 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The Skip() family of methods is used to ignore items in a sequence until either a certain number are

passed, or until a certain condition becomes false. This makes the methods great for starting a

sequence at a point possibly other than the first item of the original sequence.

Skip(int count)

Ignores the specified number of items and returns a sequence starting at the item after the last

skipped item (if any).

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { //Skip - Simple int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var allButFirst4Numbers = numbers.Skip(4); Console.WriteLine("All but first 4 numbers:"); foreach (var n in allButFirst4Numbers) { Console.WriteLine(n); } Console.ReadLine(); } } }

OutPut:

Page 154: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

154 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

LINQ with Order by?

Orderby. An orderby clause adds sorting to a query. It imposes a sorting algorithm to the expression's

result. In the C# language, this clause is compiled to the OrderBy method. But often the clearest way to

use the OrderBy method is with a clause.

Example. In this first section, we look at an example of the orderby clause. Please note how the "using

System.Linq" directive is present at the top of the program. This is required because LINQ-specific

features (extension methods) are used.

Here:The three query expressions use an orderby element, orderby element ascending, and orderby

element descending syntax.

Also:The identifier "element" is entirely arbitrary, and it is just declared in each individual query.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { ////OrderBy string[] words = { "cherry", "apple", "blueberry" }; var sortedWords = from w in words orderby w

Page 155: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

155 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

select w; Console.WriteLine("The sorted list of words:"); foreach (var w in sortedWords) { Console.WriteLine(w); } //descending double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; var sortedDoubles = from d in doubles orderby d descending select d; Console.WriteLine("The doubles from highest to lowest:"); foreach (var d in sortedDoubles) { Console.WriteLine(d); } Console.ReadLine(); } } }

OutPut:

LINQ with Group By?

GroupBy transforms a collection into groups. Each group has a key. With this method from the

System.Linq namespace, you can do this in your C# program on many collections. We examine the

GroupBy method on a collection of numbers.

Page 156: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

156 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Example. We are using the method syntax available in the System.Linq namespace. We call GroupBy

with the argument being a lambda expression. Each element is identified as 'a' in the lambda expression

(a => IsEven(a)).

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { //GroupBy int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var numberGroups = from n in numbers group n by n % 5 into g select new { Remainder = g.Key, Numbers = g }; Console.WriteLine("Remainders"); foreach (var g in numberGroups) { Console.WriteLine(g.Remainder); } Console.ReadLine(); } } }

OutPut:

Page 157: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

157 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

LINQ with Distinct?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { //Distinct int[] factors = { 2, 2, 3, 5, 5 }; var uniqueFactors = factors.Distinct(); Console.WriteLine("factors:"); foreach (var f in uniqueFactors) { Console.WriteLine(f); } Console.ReadLine(); } } }

OutPut:

Page 158: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

158 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

LINQ with Union?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { //Union int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var uniqueNumbers = numbersA.Union(numbersB); Console.WriteLine("Unique numbers from both arrays:"); foreach (var n in uniqueNumbers) { Console.WriteLine(n); } Console.ReadLine(); } } }

OutPut:

Page 159: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

159 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

LINQ with intersect?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { ////Intersect int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var commonNumbers = numbersA.Intersect(numbersB); Console.WriteLine("Common numbers shared by both arrays:"); foreach (var n in commonNumbers) { Console.WriteLine(n); } Console.ReadLine(); } } }

Page 160: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

160 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

OutPut:

LINQ with Except?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { //Except int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB); Console.WriteLine("Numbers in first array but not second array:"); foreach (var n in aOnlyNumbers) { Console.WriteLine(n); } Console.ReadLine(); } } }

OutPut:

Page 161: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

161 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

LINQ with First?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { ///First string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; string startsWithO = strings.First(); Console.WriteLine(startsWithO); //First with condition string startsWith1 = strings.First(s => s[0] == 'o'); Console.WriteLine("A string starting with 'o': {0}", startsWith1); Console.ReadLine(); } } }

OutPut:

Page 162: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

162 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

LINQ with FirstOrDefault?

The SingleOrDefault() method returns a single specific element of a sequence or default value if that

element is not found in the sequence. Whenever you use SingleOrDefault, you clearly state that the

query should result in at most a single result.

The FirstOrDefault() method returns a first specific element of a sequence or default value if that

element is not found in the sequence. Whenever FirstOrDefault is used, the query can return any

amount of results but you state that you only want the first one.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { //FirstOrDefault int[] numbers = { 1, 2, 3 }; int firstNumOrDefault = numbers.FirstOrDefault(); Console.WriteLine(firstNumOrDefault); Console.ReadLine(); } } }

Page 163: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

163 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

OutPut:

LINQ with All?

All is an extension method. It tells you if all the elements in a collection match a certain condition.

It is part of the System.Linq namespace in the .NET Framework. It returns true or false.

Example. To begin, include the System.Linq namespace. Next, pass in a lambda expression to the

All method. This lambda must receive one parameter (the type of element in the collection), and return

one bool (whether it matches the condition)

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { ////All int[] numbers = { 1, 11, 3, 19, 41, 65, 19 }; bool onlyOdd = numbers.All(n => n % 2 == 1); Console.WriteLine("The list contains only odd numbers: {0}", onlyOdd); Console.ReadLine(); } } }

Page 164: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

164 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

OutPut:

LINQ with Count?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { ////Count int[] factors = { 2, 2, 3, 5, 5 }; int uniqueFactors = factors.Distinct().Count(); Console.WriteLine("There are {0} unique factors", uniqueFactors); Console.ReadLine(); } } }

OutPut:

Page 165: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

165 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

LINQ with Sum?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { //Sum int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; double numSum = numbers.Sum(); Console.WriteLine("The sum of the numbers is {0}.", numSum); Console.ReadLine(); } } }

OutPut:

LINQ with Min, Max and Average?

using System; using System.Collections; using System.Collections.Generic;

Page 166: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

166 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Program { static void Main(string[] args) { //Min int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int minNum = numbers.Min(); Console.WriteLine("The minimum number is {0}.", minNum); Console.ReadLine(); //Max int maxNum = numbers.Max(); Console.WriteLine("The maximum number is {0}.", maxNum); Console.ReadLine(); //Average double averageNum = numbers.Average(); Console.WriteLine("The average number is {0}.", averageNum); Console.ReadLine(); } } }

OutPut:

Page 167: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

167 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

LINQ with Join?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //LINQ Language Integrated Query,enables developer to work with Sql Server queries in C# langauage //LINQ to entities helps us to work with Objects and perform sql kind of operations on given objects. class Product { public string Name { get; set; } public int CategoryID { get; set; } } class Category { public string Name { get; set; } public int ID { get; set; } } class Program { static void Main(string[] args) { ////Joins List<Category> categories = new List<Category>() { new Category(){Name="Beverages", ID=001}, new Category(){ Name="Condiments", ID=002}, new Category(){ Name="Vegetables", ID=003}, new Category() { Name="Grains", ID=004}, new Category() { Name="Fruit", ID=005} }; List<Product> products = new List<Product>() { new Product{Name="Cola", CategoryID=001}, new Product{Name="Tea", CategoryID=001}, new Product{Name="Mustard", CategoryID=002}, new Product{Name="Pickles", CategoryID=002}, new Product{Name="Carrots", CategoryID=003}, new Product{Name="Bok Choy", CategoryID=003}, new Product{Name="Peaches", CategoryID=005}, new Product{Name="Melons", CategoryID=005}, };

Page 168: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

168 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

var innerJoinQuery = from category in categories join prod in products on category.ID equals prod.CategoryID select new { Category = category.ID, Product = prod.Name }; Console.WriteLine("InnerJoin:"); // Execute the query. Access results // with a simple foreach statement. foreach (var item in innerJoinQuery) { Console.WriteLine("{0,-10}{1}", item.Product, item.Category); } Console.WriteLine(System.Environment.NewLine); Console.ReadLine(); } } }

OutPut:

About Delegate?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook

Page 169: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

169 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{ //Delegate acts as a function pointer which helps us to call method. //Declare a delagate public delegate void PrintDelegate(string str); class Program { static void Main(string[] args) { //Create instance of delagate to call method and specify the name of the method to call PrintDelegate del = new PrintDelegate(Print); //Call Method by invoking Delegate del("From Delegate"); Console.ReadLine(); } public static void Print(string str) { Console.WriteLine(str); } } }

OutPut:

About Multicast Delegate or chaining delegates?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //Multi-cast Delegate helps to call multiple methods with single delegate. //Declare a delagate public delegate void SampleDelegate();

Page 170: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

170 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

class Program { static void Main(string[] args) { SampleDelegate del1, del2, del3, del4; del1 = new SampleDelegate(SamplemethodOne); del2 = new SampleDelegate(SamplemethodTwo); del3 = new SampleDelegate(SamplemethodThree); del4 = del1 + del2 + del3; //SampleDelegate del= new SampleDelegate(SamplemethodOne); //del += SamplemethodTwo; //del += SamplemethodThree; del4(); Console.ReadLine(); } public static void SamplemethodOne() { Console.WriteLine("Print in Sample method One"); } public static void SamplemethodTwo() { Console.WriteLine("Print in Sample method Two"); } public static void SamplemethodThree() { Console.WriteLine("Print in Sample method Three"); } } }

OutPut:

Page 171: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

171 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Asynchronous Method call with Delegates?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; namespace KnackHook { //Asynchronous Method call-Executing multiple methods at same time is called as Asynchronous Method calling. //Declare a delagate public delegate void SampleDelegate_Async(); class Program { static void Main(string[] args) { SampleDelegate_Async del1, del2, del3; del1 = new SampleDelegate_Async(M1); del2 = new SampleDelegate_Async(M2); del3 = new SampleDelegate_Async(M3); //synchronous Method Calling //del1(); //del2(); //del3(); //or //del1.Invoke(); //del2.Invoke(); //del3.Invoke(); ////Asynchronous Method Calling without need of return value //Place break point and see the difference del1.BeginInvoke(null, null); del2.BeginInvoke(null, null); del3.BeginInvoke(null, null); Console.ReadLine(); } public static void M1() {

Page 172: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

172 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine("Print in Sample method One"); } public static void M2() { Console.WriteLine("Print in Sample method Two"); } public static void M3() { Console.WriteLine("Print in Sample method Three"); } } }

OutPut:

About Asynchronous Method call with return value?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; namespace KnackHook { //Asynchronous Method call-Executing multiple methods at same time is called as Asynchronous Method calling. public delegate void SampleDelegate_Async(); //Declare a delagate public delegate int SampleDelegate_Async_WithReturnValue(); class Program { static void Main(string[] args) { ////Asynchronous Method Calling with return value

Page 173: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

173 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

SampleDelegate_Async_WithReturnValue del4 = new SampleDelegate_Async_WithReturnValue(M4); IAsyncResult async = del4.BeginInvoke(null, null); int sum = del4.EndInvoke(async); Console.WriteLine("Sum is: {0}", sum); ////Asynchronous Method Calling with return value and IsCompleted Method SampleDelegate_Async_WithReturnValue del5 = new SampleDelegate_Async_WithReturnValue(M4); IAsyncResult async1 = del5.BeginInvoke(null, null); //loop until the method is complete while (!async.IsCompleted) { Console.WriteLine("Not Completed"); } int sum1 = del5.EndInvoke(async); Console.WriteLine("Sum is: {0}", sum1); ////Asynchronous Method Calling with return value and IsCompleted Method after EndInvoke SampleDelegate_Async_WithReturnValue del6 = new SampleDelegate_Async_WithReturnValue(M4); IAsyncResult async2 = del6.BeginInvoke(null, null); int sum2 = del6.EndInvoke(async); Console.WriteLine("Sum is: {0}", sum2); //loop until the method is complete while (!async.IsCompleted) { Console.WriteLine("Not Completed"); } ////Asynchronous Method Calling to call another method once current Method execution completed SampleDelegate_Async del7 = new SampleDelegate_Async(M1); IAsyncResult async3 = del7.BeginInvoke(new AsyncCallback(M5), null); ////Asynchronous Method Calling to call another method once current Method execution completed SampleDelegate_Async del8 = new SampleDelegate_Async(M1); IAsyncResult async4 = del8.BeginInvoke(new AsyncCallback(M6), "Test Message"); Console.ReadLine(); }

Page 174: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

174 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

public static void M1() { for (int i = 0; i < 100; i++) { Console.WriteLine("M1 {0}", i); } } public static void M2() { for (int i = 0; i < 100; i++) { Console.WriteLine("M2 {0}", i); } } public static void M3() { for (int i = 0; i < 100; i++) { Console.WriteLine("M3 {0}", i); } } public static int M4() { int sum = 0; for (int i = 0; i < 100; i++) { sum += i; ; } return sum; } public static void M5(IAsyncResult async) { Console.WriteLine("Method Completed!"); } public static void M6(IAsyncResult async) { AsyncResult ar = (AsyncResult)async; SampleDelegate_Async del = (SampleDelegate_Async)ar.AsyncDelegate;

Page 175: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

175 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

del.EndInvoke(async); //make use of the state object. string msg = (string)async.AsyncState; Console.WriteLine("Text is: {0}", msg); } } }

OutPut:

Page 176: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

176 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Anonymous method call?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; namespace KnackHook { //Anonymous Method call-we can create the anonymous methods in C# using delegates. A method whcih doesn't have any name is called a Anonymous method. public delegate void SampleDelegate_Anonymous(); public delegate void SampleDelegate_Anonymous2(int a, int b); class Program { static void Main(string[] args) { SampleDelegate_Anonymous del1 = delegate { int a = 10; int b = 20; Console.WriteLine("Sume of 2 numbers is:{0}", a + b); }; del1(); SampleDelegate_Anonymous2 del2 = delegate(int x, int y) { int a = x; int b = y; Console.WriteLine("Sume of 2 numbers is:{0}", a + b); }; del2(20, 30); Console.ReadLine(); }

Page 177: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

177 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

public static void SamplemethodOne() { Console.WriteLine("Print in Sample method One"); } public static void SamplemethodTwo() { Console.WriteLine("Print in Sample method Two"); } public static void SamplemethodThree() { Console.WriteLine("Print in Sample method Three"); } } }

OutPut:

About Reflection?

Reflection objects are used for obtaining type information at runtime. The classes that give

access to the metadata of a running program are in the System.Reflection namespace.

The System.Reflection namespace contains classes that allow you to obtain information

about the application and to dynamically add types, values, and objects to the application.

Applications of Reflection

Reflection has the following applications:

It allows view attribute information at runtime.

It allows examining various types in an assembly and instantiate these types.

Page 178: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

178 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

It allows late binding to methods and properties

It allows creating new types at runtime and then performs some tasks using those types.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; namespace KnackHook { //Reflection is the process of getting type information of a class/assembly at runtime. //Following program illustrate the entire reflection. public class Test { public string name = "Madhan"; public string Address = "Hyderabad"; public int sno { get; set; } public Test(int a) { } public int Add(int x, int y) { return x + y; } public int Subtract(int x, int y) { return x - y; } public void ShowMessage() { Console.WriteLine("Test"); } } class Program { static void Main(string[] args) { Type t = typeof(Test);

Page 179: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

179 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine(t.Name); Console.WriteLine(t.FullName); Console.WriteLine(t.Assembly); //foreach (var m in t.GetConstructors()) //{ // Console.WriteLine(m.Name); //} foreach (var m in t.GetMethods()) { Console.WriteLine(m.Name); } //Get field information //Get all fields information FieldInfo[] info = t.GetFields(); foreach (FieldInfo field in info) { Console.WriteLine(field.Name); } //Get Property information //Type type = typeof(Test); //PropertyInfo readWriteInfo = type.GetProperty("sno"); //Console.WriteLine(readWriteInfo.Name); Type type = typeof(Test); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { Console.WriteLine(property.Name); } //Constructor Information Type type11 = typeof(Test); ConstructorInfo[] ctrs = type11.GetConstructors(); foreach (ConstructorInfo ctr in ctrs) { Console.WriteLine(ctr); }

Page 180: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

180 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//Getting the Current Assembly Assembly asm = Assembly.GetExecutingAssembly(); Console.WriteLine(asm.FullName); //Loading Assemblies from Disk Assembly asm1 = Assembly.LoadFrom(@"C:\Test\MyAssembly.dll"); //Obtaining the Types in an Assembly Assembly asm2 = Assembly.GetExecutingAssembly(); Type[] types = asm2.GetTypes(); Console.WriteLine(types.Length); Console.WriteLine(types[0].Name); ////Activator Class Assembly asm3 = Assembly.LoadFile(@"c:\test\MyAssembly.dll"); Type type1 = asm3.GetType("Assembly.Class"); object obj = Activator.CreateInstance(type1); Console.WriteLine(obj.ToString()); //////Setting Property Values Type type3 = typeof(Test); object obj1 = Activator.CreateInstance(type3); PropertyInfo sno = type.GetProperty("sno"); sno.SetValue(obj, 22, null); string name = (string)sno.GetValue(obj, null); //invoking method Type testType = typeof(Test); object testInstance = Activator.CreateInstance(testType); MethodInfo toInvoke = testType.GetMethod("ShowMessage"); toInvoke.Invoke(testInstance, null); } } }

About Basics of Threading?

Page 181: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

181 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If

your application involves complicated and time consuming operations, then it is often helpful to set

different execution paths or threads, with each thread performing a particular job.

Threads are lightweight processes. One common example of use of thread is implementation of

concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and

increase efficiency of an application.

So far we wrote the programs where a single thread runs as a single process which is the running

instance of the application. However, this way the application can perform one job at a time. To make it

execute more than one task at a time, it could be divided into smaller threads.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //Thread is a light weight process. A process has at least one thread which commonly called as main thread, //which actually executes application code. A single process can have multiple threads. _ class Program { static void Main(string[] args) { //Normal program without thread implementation(synchronous method excution) Method1(); Method2(); //Execute both of the methods using threading(asyncronous method execution) //Namespace used for threading is System.Threading; //Creating threading object by using thread class Thread objthread1 = new Thread(Method1); Thread objthread2 = new Thread(Method2); //Printing thread information

Page 182: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

182 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine("Current Thread Informations\n"); objthread1.Name = "Method 1 Thread"; Console.WriteLine("Thread Name: {0}", objthread1.Name); Console.WriteLine("Thread Status: {0}", objthread1.IsAlive); Console.WriteLine("Priority: {0}", objthread1.Priority); //start the thread objthread1.Start(); //objthread2.Priority = ThreadPriority.Highest; objthread2.Start(); //ParameterizedThreadStart Delegate: Program p = new Program(); Console.WriteLine("Enter range value"); object target = Console.ReadLine(); ParameterizedThreadStart pt = new ParameterizedThreadStart(p.EvenNumbers); Thread t1 = new Thread(pt); t1.Start(target); Console.ReadLine(); ////Alternative way to send parameters to method Program p1 = new Program(); Console.WriteLine("Enter range value"); object target1 = Console.ReadLine(); Thread t2 = new Thread(p1.EvenNumbers); //Needs to comment below Even Numbers method. t2.Start(target); Console.ReadLine(); //Main Thread and Child thread execution Program p2 = new Program(); Console.WriteLine("Main Thread Started"); Thread T3 = new Thread(Method1); T3.Start();

Page 183: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

183 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Thread T2 = new Thread(Method2); T2.Start(); Console.WriteLine("Main Thread Completed"); Console.ReadLine(); } static void Method1() { for (int i = 0; i <= 10; i++) { Console.WriteLine("Method One Executed " + i.ToString()); } } static void Method2() { for (int i = 0; i <= 10; i++) { Console.WriteLine("Method Two Executed " + i.ToString()); } } public void EvenNumbers(object target) { int number = 0; if (int.TryParse(target.ToString(), out number)) { for (int i = 0; i <= number; i++) { if (i % 2 == 0) Console.WriteLine("Even Numbers:" + "\n" + i); } } } } }

OutPut:

Page 184: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

184 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Background thread?

1. Foreground Thread

Foreground threads are those threads that keep running even after the application exits or

quits.

It has the ability to prevent the current application from terminating.

Page 185: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

185 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The CLR will not shut down the application until all Foreground Threads have stopped.

2. Background Thread

Background Threads are those threads that will quit if our main application quits. In short, if our

main application quits, the background thread will also quit.

Background threads are views by the CLR and if all foreground threads have terminated, any and

all background threads are automatically stopped when the application quits.

By default every thread we create is a Foreground Thread.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //Thread is a light weight process. A process has at least one thread which commonly called as main thread, //which actually executes application code. A single process can have multiple threads. _ class Program { static void Main(string[] args) { //Non-background thread //Thread t = new Thread(myFun); //t.Name = "Thread1"; //t.IsBackground = false; //t.Start(); //Console.WriteLine("Main thread Running"); ////Console.ReadLine(); ////background thread Thread t = new Thread(myFun); t.Name = "Thread1"; t.IsBackground = true; t.Start(); Console.WriteLine("Main thread Running");

Page 186: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

186 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} static void myFun() { Console.WriteLine("Thread {0} started", Thread.CurrentThread.Name); Thread.Sleep(10000); Console.WriteLine("Thread {0} completed", Thread.CurrentThread.Name); } } }

OutPut:

About Thread lifecycle?

The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends

when the thread is terminated or completes execution.

Following are the various states in the life cycle of a thread:

The Unstarted State: It is the situation when the instance of the thread is created but the Start

method is not called.

The Ready State: It is the situation when the thread is ready to run and waiting CPU cycle.

The Not Runnable State: A thread is not executable, when:

o Sleep method has been called

o Wait method has been called

o Blocked by I/O operations

The Dead State: It is the situation when the thread completes execution or is aborted.

using System; using System.Collections; using System.Collections.Generic;

Page 187: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

187 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //Thread is a light weight process. A process has at least one thread which commonly called as main thread, //which actually executes application code. A single process can have multiple threads. _ class Program { static void Main(string[] args) { //threading life cycle //sleep:Suspends the current thread for the specified number of milliseconds. Thread objthread1 = new Thread(Method1); Thread objthread2 = new Thread(Method2); ////start the thread objthread1.Start(); Thread.Sleep(2000); objthread2.Start(); //Console.ReadLine(); //join:Blocks the calling thread until a thread terminates. Thread objthread3 = new Thread(Method1); Thread objthread4 = new Thread(Method2); //start the thread objthread3.Start(); //objthread1.Join(); objthread4.Start(); Console.ReadLine(); } static void Method1() { for (int i = 0; i <= 10; i++) { Console.WriteLine("Method One Executed " + i.ToString());

Page 188: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

188 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} } static void Method2() { for (int i = 0; i <= 10; i++) { Console.WriteLine("Method Two Executed " + i.ToString()); } } } }

OutPut:

Page 189: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

189 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About difference b/w Abstarct class and Interface?

Or

When to use Abstarct class and Interface?

An Abstract class doesn't provide full abstraction but an interface does provide full abstraction;

i.e. both a declaration and a definition is given in an abstract class but not so in an interface.

Using Abstract we can not achieve multiple inheritance but using an Interface we can achieve

multiple inheritance.

Page 190: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

190 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

We can not declare a member field in an Interface.

We can not use any access modifier i.e. public , private , protected , internal etc. because within

an interface by default everything is public.

An Interface member cannot be defined using the keyword static, virtual, abstract or sealed

A) Abstract Class : We can not create an object of an abstract class and can call the method

of abstract class with the help of class name only

B) An Interface : The syntax of an Interface looks like this:

interface

{

//Interface member

}

NOTE :

An Interface member can not contain code bodies.

Type definition members are forbidden.

Properties are defined in an interface with the help of an access block get and set, which are

permitted for the property.

e.g. Interface myInterface

{

int myint

{

get;

set;

}

}

using System; using System.Collections;

Page 191: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

191 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //1.Absract class :Contains instace and abstarct methods,if you know the common functionality and it's implementation of your classes then best choice is Abstract class //Here WindowsPhone class having the common functionality for all of it's phone like Call(),SMS() and Wifi() //but Color,Price and Brand have specific for each type of Windows Phone abstract class WindowsPhone { public void Call() { Console.WriteLine("Call started!"); } public void SMS() { Console.WriteLine("SMS started!"); } public void Wifi() { Console.WriteLine("Wifi started!"); } public abstract void Color(); public abstract void Price(); public abstract void Brand(); } //Lumia 510 class WindowsPhone_Lumia510 : WindowsPhone { public override void Color() { Console.WriteLine("Color is white"); } public override void Price() { Console.WriteLine("Price is 5000"); } public override void Brand() { Console.WriteLine("Brnad is Lumia 510"); }

Page 192: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

192 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//you cal also provide necessary methodes for your derived classes public void LaunchDate() { Console.WriteLine("Launch Date is" + DateTime.Now); } } //Lumia 710 class WindowsPhone_Lumia710 : WindowsPhone { public override void Color() { Console.WriteLine("Color is white"); } public override void Price() { Console.WriteLine("Price is 7000"); } public override void Brand() { Console.WriteLine("Brnad is Lumia 710"); } //you cal also provide necessary methodes for your derived classes public void LaunchDate() { Console.WriteLine("Launch Date is" + DateTime.Now); } } ////Lets use the same scenario with the interface and see ////1.Interface :Contains only abstarct methods,if you know the functionality of your classes but don't know the implementation then best choice is interface class ////implement the same scenario and see the typicality of interface interface WindowsPhone { void Call(); void SMS(); void Wifi(); void Color(); void Price(); void Brand(); } //Lumia 510

Page 193: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

193 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

class WindowsPhone_Lumia510 : WindowsPhone { //Even though all these are common functionality we have to implement in all derived classes public void Call() { Console.WriteLine("Call Started!"); } public void SMS() { Console.WriteLine("SMS Started!"); } public void Wifi() { Console.WriteLine("Wifi Started!"); } public void Color() { Console.WriteLine("Color is white"); } public void Price() { Console.WriteLine("Price is 5000"); } public void Brand() { Console.WriteLine("Brnad is Lumia 510"); } } //Lumia 710 class WindowsPhone_Lumia710 : WindowsPhone { //Even though all these are common functionality we have to implement in all derived classes public void Call() { Console.WriteLine("Call Started!"); } public void SMS() { Console.WriteLine("SMS Started!"); }

Page 194: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

194 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

public void Wifi() { Console.WriteLine("Wifi Started!"); } public void Color() { Console.WriteLine("Color is white"); } public void Price() { Console.WriteLine("Price is 7000"); } public void Brand() { Console.WriteLine("Brnad is Lumia 710"); } } class Program { static void Main(string[] args) { WindowsPhone_Lumia710 wp710 = new WindowsPhone_Lumia710(); wp710.Brand(); wp710.Call(); wp710.Color(); wp710.LaunchDate(); wp710.Price(); wp710.SMS(); wp710.Wifi(); Console.ReadLine(); } } }

OutPut:

Incase of abstract class

Page 195: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

195 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Incase of interface

About where to use interface?

Interfaces are a powerful programming tool because they let you separate the definition of objects from

their implementation. Interfaces and class inheritance each have advantages and disadvantages, and

you may end up using a combination of both in your projects. This page and When to Use Inheritance

help you determine which approach is best for your situation.

Flexibility in Implementation

There are several other reasons why you might want to use interfaces instead of class inheritance:

Interfaces are better suited to situations in which your applications require many possibly

unrelated object types to provide certain functionality.

Interfaces are more flexible than base classes because you can define a single implementation

that can implement multiple interfaces.

Interfaces are better in situations in which you do not have to inherit implementation from a

base class.

Page 196: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

196 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Interfaces are useful when you cannot use class inheritance. For example, structures cannot

inherit from classes, but they can implement interfaces.

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //Assume that Windows trying to introduce new features for his smart phone 810 like MMS and Video call.but these features will not support for //510 and 710 amobiles //if you add those features as new methods in Windows Phone Abstract class we need to develop those methods in all implemetation classes. abstract class WindowsPhone { public void Call() { Console.WriteLine("Call started!"); } public void SMS() { Console.WriteLine("SMS started!"); } public void Wifi() { Console.WriteLine("Wifi started!"); } public abstract void Color(); public abstract void Price(); public abstract void Brand(); //Assume that if we add those new features to WindowsPhone Abstarct class public abstract void MMS(); public abstract void VideoCall(); } //Another way is create one new Abstract class as WindowsAdvancedFeatures and place all your news feature methods in side it

Page 197: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

197 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//but problem with that approach is multiple class inheritance doesn't support in C# abstract class WindowsPhone { public void Call() { Console.WriteLine("Call started!"); } public void SMS() { Console.WriteLine("SMS started!"); } public void Wifi() { Console.WriteLine("Wifi started!"); } public abstract void Color(); public abstract void Price(); public abstract void Brand(); } abstract class WindowsAdvancedFeatures { public abstract void MMS(); public abstract void VideoCall(); } //Lumia 510 class WindowsPhone_Lumia510 : WindowsPhone { public override void Color() { Console.WriteLine("Color is white"); } public override void Price() { Console.WriteLine("Price is 5000"); } public override void Brand() { Console.WriteLine("Brnad is Lumia 510"); }

Page 198: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

198 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//you cal also provide necessary methodes for your derived classes public void LaunchDate() { Console.WriteLine("Launch Date is" + DateTime.Now); } } //Lumia 710 class WindowsPhone_Lumia710 : WindowsPhone { public override void Color() { Console.WriteLine("Color is white"); } public override void Price() { Console.WriteLine("Price is 7000"); } public override void Brand() { Console.WriteLine("Brnad is Lumia 710"); } //you cal also provide necessary methodes for your derived classes public void LaunchDate() { Console.WriteLine("Launch Date is" + DateTime.Now); } } //Lumia 810 //But C# doesn't support Multiple inheritance class WindowsPhone_Lumia810 : WindowsPhone, WindowsAdvancedFeatures { public override void Color() { Console.WriteLine("Color is white"); } public override void Price() { Console.WriteLine("Price is 8000"); } public override void Brand() { Console.WriteLine("Brnad is Lumia 810");

Page 199: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

199 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} public override void MMS() { Console.WriteLine("MMS Started"); } public override void VideoCall() { Console.WriteLine("Video Call Started"); } //you cal also provide necessary methodes for your derived classes public void LaunchDate() { Console.WriteLine("Launch Date is" + DateTime.Now); } } //if you add those features as new methods in Windows Phone Abstract class we need to develop those methods in all implemetation classes. //Another way is create one new Abstract class as WindowsAdvancedFeatures and place all your news feature methods in side it //but problem with that approach is multiple class inheritance doesn't support in C# //Now Use interface to achive the new functionality abstract class WindowsPhone { public void Call() { Console.WriteLine("Call started!"); } public void SMS() { Console.WriteLine("SMS started!"); } public void Wifi() { Console.WriteLine("Wifi started!"); } public abstract void Color(); public abstract void Price(); public abstract void Brand();

Page 200: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

200 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} interface WindowsAdvancedFeatures { void MMS(); void VideoCall(); } //Lumia 510 class WindowsPhone_Lumia510 : WindowsPhone { public override void Color() { Console.WriteLine("Color is white"); } public override void Price() { Console.WriteLine("Price is 5000"); } public override void Brand() { Console.WriteLine("Brnad is Lumia 510"); } //you cal also provide necessary methodes for your derived classes public void LaunchDate() { Console.WriteLine("Launch Date is" + DateTime.Now); } } //Lumia 710 class WindowsPhone_Lumia710 : WindowsPhone { public override void Color() { Console.WriteLine("Color is white"); } public override void Price() { Console.WriteLine("Price is 7000"); } public override void Brand() {

Page 201: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

201 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine("Brnad is Lumia 710"); } //you cal also provide necessary methodes for your derived classes public void LaunchDate() { Console.WriteLine("Launch Date is" + DateTime.Now); } } //Lumia 810 //with one interface and class we can implement multiple inheritance class WindowsPhone_Lumia810 : WindowsPhone, WindowsAdvancedFeatures { public override void Color() { Console.WriteLine("Color is white"); } public override void Price() { Console.WriteLine("Price is 8000"); } public override void Brand() { Console.WriteLine("Brnad is Lumia 810"); } public void MMS() { Console.WriteLine("MMS Started"); } public void VideoCall() { Console.WriteLine("Video Call Started"); } //you cal also provide necessary methodes for your derived classes public void LaunchDate() { Console.WriteLine("Launch Date is" + DateTime.Now); } } ////Lets assume that where use really use the interface concept

Page 202: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

202 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

////1.Interface :Contains only abstarct methods,if you know the functionality of your classes but don't know the implementation then best choice is interface class ////Assume that i am building an application to work with all phones and all phones having different functionality interface Phone { void Call(); void SMS(); void Wifi(); void Color(); void Price(); void Brand(); } interface Feature { void MMS(); void VideoCall(); } //Windows class WindowsPhone : Phone { //Even though all these are common functionality we have to implement in all derived classes public void Call() { Console.WriteLine("Call Started!"); } public void SMS() { Console.WriteLine("SMS Started!"); } public void Wifi() { Console.WriteLine("Wifi Started!"); } public void Color() { Console.WriteLine("Color is white"); } public void Price() { Console.WriteLine("Price is 5000"); }

Page 203: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

203 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

public void Brand() { Console.WriteLine("Brnad is Windows"); } } //Apple class Apple : Phone { //Even though all these are common functionality we have to implement in all derived classes public void Call() { Console.WriteLine("Call Started!"); } public void SMS() { Console.WriteLine("SMS Started!"); } public void Wifi() { Console.WriteLine("Wifi Started!"); } public void Color() { Console.WriteLine("Color is white"); } public void Price() { Console.WriteLine("Price is 7000"); } public void Brand() { Console.WriteLine("Brnad is Lumia 710"); } } //Android class Android : Phone,Feature {

Page 204: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

204 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

public void Call() { Console.WriteLine("Call Started!"); } public void SMS() { Console.WriteLine("SMS Started!"); } public void Wifi() { Console.WriteLine("Wifi Started!"); } public void Color() { Console.WriteLine("Color is white"); } public void Price() { Console.WriteLine("Price is 8000"); } public void Brand() { Console.WriteLine("Brnad is Lumia 810"); } public void MMS() { Console.WriteLine("MMS Started"); } public void VideoCall() { Console.WriteLine("Video Call Started"); } } class Program { static void Main(string[] args) { WindowsPhone_Lumia710 wp710 = new WindowsPhone_Lumia710(); //wp710.Brand();

Page 205: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

205 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//wp710.Call(); //wp710.Color(); //wp710.LaunchDate(); //wp710.Price(); //wp710.SMS(); //wp710.Wifi(); Console.ReadLine(); } } }

Can an interface inherit from another interface? Answer:Yes using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { interface IA { void Print(); } interface IB:IA { void Show(); } class MyClass:IB { public void Show() { Console.WriteLine("IA"); } public void Print() { Console.WriteLine("IB"); } } class Program {

Page 206: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

206 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

static void Main(string[] args) { MyClass m = new MyClass(); m.Print(); m.Show(); Console.ReadLine(); } } }

OutPut:

Is it possible to create partial structs, interfaces and methods? Yes, it is possible to create partial structs, interfaces and methods. We can create partial structs, interfaces and methods the same way as we create partial classes. using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { //partial interface partial interface IA { void Print(); } partial interface IA { void Show(); } class MyClass:IA {

Page 207: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

207 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

public void Show() { Console.WriteLine("IA"); } public void Print() { Console.WriteLine("IB"); } } //partial struct partial struct MyStruct { public void M1() { Console.WriteLine("M1"); } } partial struct MyStruct { public void M2() { Console.WriteLine("M2"); } } //partial Method partial class PartialMethod { partial void OnSomethingHappened(string s); } // This part can be in a separate file. partial class PartialMethod { // Comment out this method and the program // will still compile. partial void OnSomethingHappened(String s) { Console.WriteLine("Something happened: {0}", s); } } class Program { static void Main(string[] args) { MyClass m = new MyClass(); m.Print();

Page 208: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

208 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

m.Show(); MyStruct s = new MyStruct(); s.M1(); s.M2(); Console.ReadLine(); } } }

OutPut:

How do you create partial methods? To create a partial method we create the declaration of the method in one part of the partial class and implementation in the other part of the partial class. The implementation is optional. If the implementation is not provided, then the method and all the calls to the method are removed at compile time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented. In summary a partial method declaration consists of two parts. The definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method. The following are the points to keep in mind when creating partial methods. 1. Partial method declarations must begin partial keyword. 2. The return type of a partial method must be void. 3. Partial methods can have ref but not out parameters. 4. Partial methods are implicitly private, and therefore they cannot be virtual. 5. Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing. What is the use of partial methods?

Page 209: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

209 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Partial methods can be used to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs. Why is it not a good idea to use Empty destructors? When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance. We cannot create instances of static classes. Can we have constructors for static classes? Yes, static classes can also have constructors. using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { static class MyClass { //static class with COnstructor static MyClass() { Console.WriteLine("Constructor"); } static public void Show() { Console.WriteLine("Show"); } static public void Print() { Console.WriteLine("Print"); } } class Program { static void Main(string[] args) {

Page 210: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

210 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//when we make a call for static class methods automatically static constructor will get execute. MyClass.Show(); MyClass.Print(); Console.ReadLine(); } } }

OutPut:

Can you prevent a class from being instantiated?

Yes, a class can be prevented from being instantiated by using a private constructor as shown in the example below. using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { class MyClass { private MyClass() { Console.WriteLine("Constructor"); } public void Show() { Console.WriteLine("Show"); } public void Print() { Console.WriteLine("Print"); }

Page 211: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

211 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} class Program { static void Main(string[] args) { //Not allow to create instance of a MyClass MyClass m = new MyClass(); Console.ReadLine(); } } }

Can a child class call the constructor of a base class? Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below. using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { class MyBaseClass { public MyBaseClass() { Console.WriteLine("Base class Constructor"); } public void Show() { Console.WriteLine("Show"); } public void Print() { Console.WriteLine("Print"); } } class MyChildClass : MyBaseClass { public MyChildClass(): base()

Page 212: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

212 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{ Console.WriteLine("Child class Constructor"); } } class Program { static void Main(string[] args) { MyChildClass m = new MyChildClass(); Console.ReadLine(); } } }

OutPut:

If a child class instance is created, which class constructor is called first - base class or child class? When an instance of a child class is created, the base class constructor is called before the child class constructor. using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { class MyBaseClass { public MyBaseClass() { Console.WriteLine("Base class Constructor");

Page 213: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

213 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} public void Show() { Console.WriteLine("Show"); } public void Print() { Console.WriteLine("Print"); } } class MyChildClass : MyBaseClass { public MyChildClass() { Console.WriteLine("Child class Constructor"); } } class Program { static void Main(string[] args) { MyChildClass m = new MyChildClass(); Console.ReadLine(); } } }

OutPut:

Can you mark static constructor with access modifiers? No, we cannot use access modifiers on static constructor. using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading;

Page 214: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

214 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System.Data.SqlClient; namespace KnackHook { static class MyClass { //static class with Constructor,will give error if it has access modifier static public MyClass() { Console.WriteLine("Constructor"); } static public void Show() { Console.WriteLine("Show"); } static public void Print() { Console.WriteLine("Print"); } } class Program { static void Main(string[] args) { //when we make a call for static class methods automatically static constructor will get execute. MyClass.Show(); MyClass.Print(); Console.ReadLine(); } } }

OutPut:

Can you have parameters for static constructors? No, static constructors cannot have parameters.

Page 215: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

215 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { static class MyClass { //static class with Constructor,will give error if it has parameters static MyClass(string s) { Console.WriteLine("Constructor"); } static public void Show() { Console.WriteLine("Show"); } static public void Print() { Console.WriteLine("Print"); } } class Program { static void Main(string[] args) { //when we make a call for static class methods automatically static constructor will get execute. MyClass.Show(); MyClass.Print(); Console.ReadLine(); } } }

OutPut:

Page 216: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

216 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

What happens if a static constructor throws an exception? If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running. Give 2 scenarios where static constructors can be used? 1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file. 2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method. If a method's return type is void, can you use a return keyword in the method? Yes, Even though a method's return type is void, you can use the return keyword to stop the execution of the method as shown in the example below. using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { class Program { static void Main(string[] args) { SayHi(); Console.ReadLine(); } public static void SayHi() {

Page 217: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

217 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine("Hi"); return; Console.WriteLine("This statement will never be executed"); } } }

OutPut:

About Dependency Injection?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { public class PaymentTerms { PaymentCalculator _calculator = new PaymentCalculator(); public decimal Price { get; set; } public decimal Deposit { get; set; } public int Years { get; set; } public decimal GetMonthlyPayment() { return _calculator.GetMonthlyPayment(Price, Deposit, Years); } } public class PaymentCalculator { public decimal GetMonthlyPayment(decimal Price, decimal Deposit, int Years) { decimal total = Price * (1 + Years * 0.1M); decimal monthly = (total - Deposit) / (Years * 12); return Math.Round(monthly, 2, MidpointRounding.AwayFromZero); } }

Page 218: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

218 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//One of the key problems with the above code is the instantiation of the PaymentCalculator object from within the PaymentTerms class. //As the dependency is initialised within the containing class, the two classes are tightly coupled. //If, in the future, several types of payment calculator are required, it will not be possible to integrate them without //modifying the PaymentTerms class. //Dependency injection reduces the problem of tight coupling by removing the instantiation of dependencies from a dependent class. //Instead, pre-constructed objects are passed to a dependent object at some time before they are required. //A class has a dependency on any other class that it uses. When one object creates another object using the new keyword, //this can result in tightly coupled code which is difficult to test, maintain and extend. //Advantages //Easy to maintain //Easy to test //East to extent //Implementation types of DI //Constructor Level //Property Level //Method Level //Interface Level class Program { static void Main(string[] args) { //Calling in normal way PaymentTerms pt = new PaymentTerms(); pt.Price = 10000; pt.Years = 4; pt.Deposit = 2500; Console.WriteLine(pt.GetMonthlyPayment()); Console.ReadLine(); } } }

OutPut:

Page 219: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

219 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About implementation of DI through the Constructor?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //1.Contructor Level public interface IPaymentCalculator { public decimal GetMonthlyPayment(decimal Price, decimal Deposit, int Years); } public class PaymentCalculator:IPaymentCalculator { public decimal GetMonthlyPayment(decimal Price, decimal Deposit, int Years) { decimal total = Price * (1 + Years * 0.1M); decimal monthly = (total - Deposit) / (Years * 12); return Math.Round(monthly, 2, MidpointRounding.AwayFromZero); } } public class PaymentTerms { IPaymentCalculator _calculator; public PaymentTerms(IPaymentCalculator calculator) { _calculator = calculator; } public decimal Price { get; set; } public decimal Deposit { get; set; } public int Years { get; set; } public decimal GetMonthlyPayment() {

Page 220: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

220 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

return _calculator.GetMonthlyPayment(Price, Deposit, Years); } } class Program { static void Main(string[] args) { //1.Constructor Level PaymentTerms pt = new PaymentTerms(new PaymentCalculator()); pt.Price = 10000; pt.Years = 4; pt.Deposit = 2500; Console.WriteLine(pt.GetMonthlyPayment()); Console.ReadLine(); } } }

OutPut:

About implementation of DI through the Property?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //2.Property Level public interface IPaymentCalculator { public decimal GetMonthlyPayment(decimal Price, decimal Deposit, int Years); }

Page 221: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

221 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

public class PaymentCalculator : IPaymentCalculator { public decimal GetMonthlyPayment(decimal Price, decimal Deposit, int Years) { decimal total = Price * (1 + Years * 0.1M); decimal monthly = (total - Deposit) / (Years * 12); return Math.Round(monthly, 2, MidpointRounding.AwayFromZero); } } public class PaymentTerms { IPaymentCalculator _calculator; public IPaymentCalculator Calculator { set { _calculator = value; } } public decimal Price { get; set; } public decimal Deposit { get; set; } public int Years { get; set; } public decimal GetMonthlyPayment() { return _calculator.GetMonthlyPayment(Price, Deposit, Years); } } class Program { static void Main(string[] args) { //2.Property Level PaymentTerms pt = new PaymentTerms(); pt.Calculator = new PaymentCalculator(); pt.Price = 10000; pt.Years = 4; pt.Deposit = 2500; Console.WriteLine(pt.GetMonthlyPayment()); Console.ReadLine(); } } }

OutPut:

Page 222: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

222 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About implementation of DI through the Method?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //3.Method Level public interface IPaymentCalculator { public decimal GetMonthlyPayment(decimal Price, decimal Deposit, int Years); } public class PaymentCalculator : IPaymentCalculator { public decimal GetMonthlyPayment(decimal Price, decimal Deposit, int Years) { decimal total = Price * (1 + Years * 0.1M); decimal monthly = (total - Deposit) / (Years * 12); return Math.Round(monthly, 2, MidpointRounding.AwayFromZero); } } public class PaymentTerms { IPaymentCalculator _calculator; public IPaymentCalculator Calculator { set { _calculator = value; } } public void Payment(IPaymentCalculator Calculator) { this._calculator = Calculator; } public decimal Price { get; set; }

Page 223: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

223 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

public decimal Deposit { get; set; } public int Years { get; set; } public decimal GetMonthlyPayment() { return _calculator.GetMonthlyPayment(Price, Deposit, Years); } } class Program { static void Main(string[] args) { ////3.Method Level PaymentTerms pt = new PaymentTerms(); pt.Payment(new PaymentCalculator()); pt.Price = 10000; pt.Years = 4; pt.Deposit = 2500; Console.WriteLine(pt.GetMonthlyPayment()); Console.ReadLine(); } } }

OutPut:

About implementation of DI through the interface?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook {

Page 224: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

224 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//4.Interface Level public interface IPaymentCalculator { decimal GetMonthlyPayment(decimal Price, decimal Deposit, int Years); } public class PaymentCalculator : IPaymentCalculator { public decimal GetMonthlyPayment(decimal Price, decimal Deposit, int Years) { decimal total = Price * (1 + Years * 0.1M); decimal monthly = (total - Deposit) / (Years * 12); return Math.Round(monthly, 2, MidpointRounding.AwayFromZero); } } interface IPaymentCalculatorInjecter { void InjectCalculator(IPaymentCalculator calculator); } public class PaymentTerms : IPaymentCalculatorInjecter { IPaymentCalculator _calculator; public void InjectCalculator(IPaymentCalculator calculator) { _calculator = calculator; } public decimal Price { get; set; } public decimal Deposit { get; set; } public int Years { get; set; } public decimal GetMonthlyPayment() { return _calculator.GetMonthlyPayment(Price, Deposit, Years); } } class Program { static void Main(string[] args) { //////4.Interface Level PaymentTerms pt = new PaymentTerms(); pt.InjectCalculator(new PaymentCalculator()); pt.Price = 10000; pt.Years = 4; pt.Deposit = 2500;

Page 225: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

225 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine(pt.GetMonthlyPayment()); Console.ReadLine(); } } }

OutPut:

About Singleton Design pattern?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //SingleTon design pattern gives an ability to create instance for a class throughout the application at once. public sealed class Logging { static Logging instance = null; static readonly object lockObj = new object(); private Logging() { } public static Logging Instance { get { lock (lockObj) { if (instance == null) { instance = new Logging(); Console.WriteLine("Object Created!"); }

Page 226: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

226 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

return instance; } } } public void ErrorLog() { Console.WriteLine("Error Logged in notepad"); } } class Program { static void Main(string[] args) { Logging obj1 = Logging.Instance; obj1.ErrorLog(); //eventhough we have created the 2 objects for Logging class only one time instance created Logging obj2 = Logging.Instance; obj2.ErrorLog(); Console.ReadLine(); } } }

OutPut:

About Factory Method design pattern?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq;

Page 227: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

227 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //Factory Method //This is a creational pattern as it is used to control class instantiation. //The factory pattern is used to replace class constructors, abstracting the process of object generation //so that the type of the object instantiated can be determined at run-time. class Lumia510 { public void Buy() { Console.WriteLine("Buy Lumia510 phone"); } } class Lumia610 { public void Buy() { Console.WriteLine("Buy Lumia610 phone"); } } //Assume that there is new phone want to add to my store //In this case client code needs to change to create new object for Lumia710,by adding new case statement in switch class. class Lumia710 { public void Buy() { Console.WriteLine("Buy Lumia710 phone"); } } class Program { static void Main(string[] args) { ////Getting input from the user and to buy perticular product

Page 228: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

228 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Console.WriteLine("Enter category to buy phone"); string ph = Console.ReadLine(); switch (ph) { case "Lumia510": Lumia510 wp = new Lumia510(); wp.Buy(); break; case "Lumia610": Lumia610 ap = new Lumia610(); ap.Buy(); break; //need to change the client code and add one more case statement case "Lumia710": Lumia710 app = new Lumia710(); app.Buy(); break; default: Console.WriteLine("Wrong Entry"); break; } Console.ReadLine(); } } }

OutPut:

To avoid client code changes, we need Factory Design pattern.

using System; using System.Collections; using System.Collections.Generic; using System.Text;

Page 229: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

229 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; namespace KnackHook { //Factory Method //This is a creational pattern as it is used to control class instantiation. //The factory pattern is used to replace class constructors, abstracting the process of object generation //so that the type of the object instantiated can be determined at run-time. //to avoid this kind of problems create FactoryInterface public interface IWindows { void Buy(); } class Lumia510 : IWindows { public void Buy() { Console.WriteLine("Buy Lumia510 phone"); } } class Lumia610 : IWindows { public void Buy() { Console.WriteLine("Buy Lumia610 phone"); } } //Assume that there is new phone want to add to my store class Lumia710 : IWindows { public void Buy() { Console.WriteLine("Buy Lumia710 phone"); } } public class FactoryChoice { static public IWindows getChoiceObj(string cChoice)

Page 230: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

230 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{ IWindows objChoice = null; switch (cChoice) { case "Lumia510": objChoice = new Lumia510(); break; case "Lumia610": objChoice = new Lumia610(); break; //we can add any no.of cases as required ,no need to change the client code. case "Lumia710": objChoice = new Lumia710(); break; default: Console.WriteLine("Wrong Entry"); break; } return objChoice; } } class Program { static void Main(string[] args) { Console.WriteLine("Enter category to buy phone"); string ph = Console.ReadLine(); IWindows objInvoice; objInvoice = KnackHook.FactoryChoice.getChoiceObj(ph); objInvoice.Buy(); Console.ReadLine(); Console.ReadLine(); } } }

OutPut:

Page 231: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

231 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

What are the Methods we can able to access with a,b,c objects in the following program?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { class A { public void M1() { } } class B:A { public void M2() { } } class Program { static void Main(string[] args) { A a = new B(); B b = new A(); B c = (B)new A(); Console.ReadLine(); } } }

Answer:

Page 232: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

232 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

a->M1

b->compile time error

c->M1, M2

In the following code finally block execute or not?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { class Program { static void Main(string[] args) { int s = sum(); Console.WriteLine(s); } public static int sum() { try { int a = 10; int b = 20; int c = a + b; return c; } catch(Exception ex) { int c = 0; Console.WriteLine(ex.Message.ToString()); return c; } finally { //code to release objects } } } }

Answer: finally block always execute even we place return keyword in exception handling mechanism

First finally block will execute and returns a value.

Page 233: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

233 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

How to implement only specified Methods in an interface?

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; using System.Data.SqlClient; namespace KnackHook { interface IA { void M1(); void M2(); void M3(); void M4(); } //if we need to implement only 2 methods of interface then mark this class a Abstract class abstract class MyClass:IA { public void M1() { Console.WriteLine("M1"); } public void M2() { Console.WriteLine("M2"); } public abstract void M3(); public abstract void M4(); } class Program { static void Main(string[] args) { } } }

Page 234: knackhook.comknackhook.com/Tutorials/CSharpTutorial.pdf · 2 | P a g e KnackHook Knowledge Holder info@knackhook.com  Table of Contents 1. About .Net

234 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com