1 P a g e. C#.Net. MakeMeSharp Enjoy unlimited learning!

Size: px
Start display at page:

Download "1 P a g e. C#.Net. MakeMeSharp Enjoy unlimited learning!"

Transcription

1 1 P a g e C#.Net

2 2 P a g e Table of Contents 1. About.Net? About.Net Framework About Common Language Runtime (CLR) and its Services? What is managed code in.net? What is unmanaged code in.net? About Common Type System? About Common Language Specification? About Framework Class Library? About Visual Studio? About Execution flow of C# Program? About Hello World! Program? About? About Write, WriteLine, Read, ReadLine and ReadKey methods? About Data Types? About difference between Decimal, Float and Double in.net? How to get Max and Min range of data types? About Data type conversion? About Boxing and Unboxing? About Operators? About Ternary Operator? About is and as Operators?... 34

3 3 P a g e 22. About Null Coalescing Operator??? About Bitwise Operators? About difference between int.parse,convert.toint32 and int.tryparse? Conditional Statements? About if? About if-else? About switch vs if-else-if? About for vs foreach? About while vs do-while? About polyndrome number? About Prime number? About Methods? About Instance method? About Static Method? About value type parameters? About reference type parameter? About out parameter? About parameter array? About Arrays? About storing different data types values in to an array? About Obsolete Attribute in C#? About Tuple in C#? About Finalize and Dispose Methods? About using keyword? About Use of New Keyword?... 62

4 4 P a g e 47. About sorting an array elements? About sorting elements with Bubble sort? About structures? About enum data type? About reversing a string? About string vs stringbuilder? About Difference b/w.tostring() and Convert.ToString()? About Recursive Method? About Collections? About ArrayList? About Hashtable? About Stack? About Difference b/w Pop() and Peek()? About Queue? About difference b/w DeQueue() and Peek()? About Generic Collection Dictionary? About Generic Collection List? About Generic Collection Queue? About Generic Collection Stack? About SortedList? About IEnumerable? About IQueryable? What's the difference between IEnumerable<T> and List<T>? About Class? About public access modifier?... 94

5 5 P a g e 72. About private Access Modifier? About protected Access Modifier? About properties? About default constructor? About parameter Constructor? About static constructor? About copy constructor? About private constructor? About static class? About abstract class? About interface? About partial class? About Data Abstraction and Encapsulation? About Method Overloading? About Operator Overloading? About Method Overriding? About Inheritance? About single inheritance? About multi-level inheritance? About multiple inheritance? About multiple inheritance through interfaces? About multiple interface with one class and one interface? About Extension Method? About indexers? About Generic Methods?

6 6 P a g e 97. About Generic Classes? About Exception Handling? About dynamic, object and var keywords? About LINQ with selection? LINQ with where condition? LINQ with select many? LINQ with Take? LINQ with TakeWhile? LINQ with Skip? LINQ with Order by? LINQ with Group By? LINQ with Distinct? LINQ with Union? LINQ with intersect? LINQ with Except? LINQ with First? LINQ with FirstOrDefault? LINQ with All? LINQ with Count? LINQ with Sum? LINQ with Min, Max and Average? LINQ with Join? About Delegate? About Multicast Delegate or chaining delegates? About Asynchronous Method call with Delegates?

7 7 P a g e 122. About Asynchronous Method call with return value? About Anonymous method call? About Reflection? About Basics of Threading? About Background thread? About Thread lifecycle? About difference b/w Abstarct class and Interface? About where to use interface? Can an interface inherit from another interface? Is it possible to create partial structs, interfaces and methods? How do you create partial methods? Why is it not a good idea to use Empty destructors? We cannot create instances of static classes. Can we have constructors for static classes? Can you prevent a class from being instantiated? Can a child class call the constructor of a base class? If a child class instance is created, which class constructor is called first - base class or child class? Can you mark static constructor with access modifiers? Can you have parameters for static constructors? What happens if a static constructor throws an exception? If a method's return type is void, can you use a return keyword in the method?

8 8 P a g e 142. About Dependency Injection? About implementation of DI through the Constructor? About implementation of DI through the Property? About implementation of DI through the Method? About implementation of DI through the interface? About Singleton Design pattern? About Factory Method design pattern? What are the Methods we can able to access with a,b,c objects in the following program? In the following code finally block execute or not? How to implement only specified Methods in an interface? 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 : 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.

9 9 P a g e 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 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.

10 10 P a g e If you have some application requiring assembly version to run properly and some of your application requires same file but having version 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 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 commandline 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.

11 11 P a g e 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

12 12 P a g e 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 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 to avoid the OutOfMemory exception. Multi-core JIT Improvements : It enhance the launch time of the application %

13 13 P a g e 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.

14 14 P a g e 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.

15 15 P a g e 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

16 16 P a g e 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

17 17 P a g e 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

18 18 P a g e 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

19 19 P a g e 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 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

20 20 P a g e 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 shortlived 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

21 21 P a g e About Hello World! Program? Console.Write("Hollo World!"); OutPut:

22 22 P a g e About? 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? //The Write() method outputs one or more values to the screen without a new line character(\n). Console.Write("About Write!");

23 23 P a g e 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!"); character ////Read() method will read only a single char and return ASCII value of that Console.Write("About Read!"); int i = Console.Read(); Console.WriteLine(i); ////ReadLine() Method reads the whole string Console.Write("About ReadLine!"); string s = 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()); OutPut:

24 24 P a g e 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 e38 to e38 Double 8 Bytes e308 to e308

25 25 P a g e Decimal 16 Bytes to 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 digits (64 bit) Decimal 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. float flt = 1F / 3; double dbl = 1D / 3; decimal dcm = 1M / 3; Console.WriteLine("float: 0 double: 1 decimal: 2", flt, dbl, dcm);

26 26 P a g e OutPut: How to get Max and Min range of data types? ////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); OutPut:

27 27 P a g e 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 builtin numeric types, such as Int32.Parse.

28 28 P a g e //Type Coversion type value //Implicit Type Conversion:Converting lower data type value to higher data int intvalue = 123; long longvalue = intvalue; Console.WriteLine("0, 1", intvalue, longvalue); type value ////Explicit Type Conversion:Converting higher data type value to lower data double doublevalue = ; int intvalue1 = Convert.ToInt32(doubleValue); Console.WriteLine("0, 1", doublevalue, intvalue1); 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.

29 29 P a g e 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. ////Boxing and Unboxing int stackvar = 12;

30 30 P a g e //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); 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

31 31 P a g e % Modulus Operator and remainder of after an integer division Increment operator increases integer value by one Decrement operator decreases integer value by one B % A = 0 A++ = 11 A-- = 9 Relational Operators Operator Description Example ==!= > < >= <= Checks if the values of two operands are equal or not, if yes then condition becomes true. Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than the value of right operand, if yes then condition becomes 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. 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 not true. (A!= B) is true. (A > B) is not true. (A < B) is true. (A >= B) is not true. (A <= B) is true.

32 32 P a g e Logical Operators Operator Description Example &&! Called Logical AND operator. If both the operands are non zero then condition becomes true. Called Logical OR Operator. If any of the two operands is non zero then condition becomes 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 false. (A B) is true.!(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 ++ --

33 33 P a g e 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. //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);

34 34 P a g e 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; class Abc class Def

35 35 P a g e //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); 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

36 36 P a g e //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); 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

37 37 P a g e Assume if A = 60; and B = 13; then in the binary format they are as follows: A = B = A&B = =12 A B = A^B = ~A = Example: using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; int A = 60;// int B = 13;// 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

38 38 P a g e Console.WriteLine("The bitwise ^ value of A^B is 0", A ^ B);//61 Console.WriteLine("The bitwise << value of A<< is 0", A << B);// Console.WriteLine("The bitwise >> value of A>>B is 0", A >> B);//0 Console.WriteLine("The bitwise ~ value of ~A is 0", ~A);//-61 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; string str1 = "9009"; string str2 = null; string str3 = " "; string str4 = " "; int finalresult; finalresult = int.parse(str1); //success

39 39 P a g e finalresult = int.parse(str2); //ArgumentNullException finalresult = int.parse(str3); //FormatException finalresult = int.parse(str4); //OverflowException 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; string str1 = "9009"; string str2 = null; string str3 = " "; string str4 = " "; int finalresult; finalresult = Convert.ToInt32(str1); // 9009 finalresult = Convert.ToInt32(str2); // 0 finalresult = Convert.ToInt32(str3); //FormatException

40 40 P a g e finalresult = Convert.ToInt32(str4); //OverflowException 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; string str1 = "9009"; string str2 = null; string str3 = " "; string str4 = " "; 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 Conditional Statements?

41 41 P a g e Conditional Statements IF IF ELSE FOR WHILE DO WHILE SWITCH FOREACH About if? if conditional statement is used to evaluate single condition 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 int Age = 30; //if-else conditional statement is used to evaluate two condition if (Age >18 ) Console.WriteLine("Eligible for vote!"); else

42 42 P a g e 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). //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"); //switch: which provides an easy way to check multiple statements

43 43 P a g e 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; OutPut: About for vs foreach?

44 44 P a g e 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. //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); ////Same using For for (int i = 0; i < myinterger.length; i++) total += myinterger[i]; ; Console.WriteLine(total);

45 45 P a g e 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. 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;

46 46 P a g e int j = 0; do total += myinterger[j]; j++; while (j < myinterger.length); Console.WriteLine("Total from Do-While: " + total); Output: About polyndrome number? //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);

47 47 P a g e if (temp == reverse) Console.WriteLine("Number is a palindrome \n"); else Console.WriteLine("Number is not a palindrome \n"); OutPut: About Prime number? //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");

48 48 P a g e 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.

49 49 P a g e 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. ////Methods //Instance Method: which needs an object to call a method Program ojver = new Program(); int c = ojver.add(5, 10); Console.WriteLine(c); public int Add(int a, int b) return a + b;

50 50 P a g e 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. ////Methods ////Static Method:which doesn't need any object to call a method int d = Add(5, 10); Console.WriteLine(d); public static int Add(int a, int b) return a + b; OutPut:

51 51 P a g e 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. ////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); static void SimpleMethod(int j) j = j + 1; Console.WriteLine("J value inside Called Method is " + j); OutPut:

52 52 P a g e 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. ////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); static void SimpleMethodRef(ref int j) j = j + 1; Console.WriteLine("J value inside Called Method is " + j); OutPut:

53 53 P a g e 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. ////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); static void SimpleMethodOut(int i, int j, out int Sum, out int Product) Sum = i + j; Product = i * j; OutPut:

54 54 P a g e 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. array ////Method Parameters ////Parameter Array:which accepts any number of parameters in the form of SimpleMethodParams(1, 2, 3, 4, 5); static void SimpleMethodParams(params int[] numbers)

55 55 P a g e 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

56 56 P a g e 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] = ; About storing different data types values in to an array? using System.Text; //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);

57 57 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; //Obsolete attribute is used to declare a method as deprecated. M1(); M2(); [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");

58 58 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; //Obsolete attribute is used to declare a method as deprecated. //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",

59 59 P a g e 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); 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.

60 60 P a g e 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.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; //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

61 61 P a g e ~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); 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 About using keyword?

62 62 P a g e 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.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; //"using" keyword helps to clear objects once execution come out of the using block. //"using" keyword helps to import namespaces. using (SqlConnection sqlcon = new SqlConnection()) sqlcon.open(); 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

63 63 P a g e 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.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; //"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!"); A a1 = new A(); a1.show(); B b1 = new B(); b1.show(); A a2 = new B(); a2.show();

64 64 P a g e 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). //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); About sorting elements with Bubble sort?

65 65 P a g e 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. //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); public static void exchange(int[] data, int m, int n) int temporary; temporary = data[m]; data[m] = data[n];

66 66 P a g e 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

67 67 P a g e 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. 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);

68 68 P a g e methods. //Structures/ Structs //Similar to classes struct can have fields, properties,constructors and //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(); 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; //enum public enum Days Sun, Mon, Tue, Wed, Thu, Fri, Sat ;

69 69 P a g e //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); About reversing a string? using System.Text; //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);

70 70 P a g e foreach (var item in strrev1) strtemp.append(item); Console.WriteLine("Reverse of a string is 0", strtemp); 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 It s an immutable Performance wise string is slow because every time it will create new instance In string we don t have append keyword String belongs to System namespace StringBuilder It s mutable Performance wise stringbuilder is high because it will use same instance of object to perform any action In StringBuilder we can use append keyword Stringbuilder belongs to System.Text namespace using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging;

71 71 P a g e using System.Reflection; using System.Threading; //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); 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.

72 72 P a g e OutPut1: Incase of uncommented str2; OutPut2: Incase of commented str2; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; //.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

73 73 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; 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)); public int factorial(int num) int result; if (num == 1) return 1; else result = factorial(num - 1) * num; return result;

74 74 P a g e 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.Collections; using System.Text; //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);

75 75 P a g e obj.insert(2,"mamidala"); foreach (var item in obj) Console.WriteLine(item); 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.Collections; using System.Text; //Hashtable is used to store non-homogeneous data types with Kay and Value pairs under a common name Hashtable obj = new Hashtable();

76 76 P a g e 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]); 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.Collections; using System.Text; //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");

77 77 P a g e obj.push("mamidala"); foreach (var item in obj) Console.WriteLine(item); 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.

78 78 P a g e using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; // 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)\t0", mys.pop()); // Displays the Stack. Console.Write("Stack values:"); PrintValues(myS); // Removes another element from the Stack. Console.WriteLine("(Dequeue)\t0", 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) \t0", mys.peek()); // Displays the Stack. Console.Write("Stack values:"); PrintValues(myS); public static void PrintValues(IEnumerable mycollection) foreach (Object obj in mycollection) Console.Write(" 0", obj);

79 79 P a g e 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);

80 80 P a g e 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.Collections; using System.Text; //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); OutPut: About difference b/w DeQueue() and Peek()? Dequeue:

81 81 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; // 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)\t0", myq.dequeue()); // Displays the Queue. Console.Write("Queue values:"); PrintValues(myQ); // Removes another element from the Queue.

82 82 P a g e Console.WriteLine("(Dequeue)\t0", 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) \t0", myq.peek()); // Displays the Queue. Console.Write("Queue values:"); PrintValues(myQ); 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.

83 83 P a g e using System.Collections; using System.Collections.Generic; using System.Text; //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]); OutPut:

84 84 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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);

85 85 P a g e lststudentint.add(4); lststudentint.add(5); //lststudent.add("student 1"); Console.WriteLine(); foreach (int dinosaur in lststudentint) Console.WriteLine(dinosaur); 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.

86 86 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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()); OutPut:

87 87 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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");

88 88 P a g e 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()); 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.Collections; using System.Collections.Generic; using System.Text; ////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");

89 89 P a g e 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); 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

90 90 P a g e 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.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; //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.

91 91 P a g e class Category public string Name get; set; public int ID get; set; 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); OutPut: About IQueryable? The IQueryable is defined as below:

92 92 P a g e 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.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; //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; 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)

93 93 P a g e Console.WriteLine("0 1", item.id, item.name); 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.Collections; using System.Collections.Generic; using System.Text; //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;

94 94 P a g e //Destructor to release objects ~Customer() //Method public void PrintFullName() Console.WriteLine("Full Name : " + _firstname + " " + _lastname); Customer cust = new Customer("Mamidala", "Madhan"); cust.printfullname(); 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.

95 95 P a g e Accessibility: Can be accessed by objects of the class Can be accessed by derived classes using System.Collections; using System.Collections.Generic; using System.Text; // 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); Customer cust = new Customer("Mamidala", "Madhan"); cust.printfullname();

96 96 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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;

97 97 P a g e //Constructor to initialize fields public Customer(string FirstName, string LastName) _firstname = FirstName; _lastname = LastName; private void PrintFullName() Console.WriteLine("Full Name : " + _firstname + " " + _lastname); Customer cust = new Customer("Mamidala", "Madhan"); //Which is not accessible out side of the class //cust.printfullname(); 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.

98 98 P a g e 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.Collections; using System.Collections.Generic; using System.Text; ////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();

99 99 P a g e CustomerDerived cust = new CustomerDerived("Madhan","Mamidala"); cust.testprint(); 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.

100 100 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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 get if (value <= 0) throw new Exception("ID not to be negative"); _id = value; return _id; public string Name set _name = value; get return _name;

101 101 P a g e public int Passmark //set // // _passmark = value; // get return _passmark; //Auto implemented properties(c# compiler automatically create private fields automatically) public int City set; get; //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 OutPut:

102 102 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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); //Default constructor Student c = new Student(); c.print();

103 103 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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()

104 104 P a g e Console.WriteLine("Name is 0 and Address is 1", Name, Address); //Parameter constructor Student c = new Student("Madhan","India"); c.print(); 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

105 105 P a g e using System.Collections; using System.Collections.Generic; using System.Text; //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"); //static constructor StaticConstructor c1 = new StaticConstructor(); StaticConstructor c2 = new StaticConstructor(); OutPut:

106 106 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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);

107 107 P a g e CopyConstructor c1 = new CopyConstructor(10, 20); CopyConstructor c2 = new CopyConstructor(c1); c1.print(); c2.print(); 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.Collections; using System.Collections.Generic; using System.Text; //Constructor //private Constructor oppose to create object for a class class PrivateConstructor

108 108 P a g e static public int b = 10; static public int c = 20; private PrivateConstructor() //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); OutPut: About static class?

109 109 P a g e 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.Collections; using System.Collections.Generic; using System.Text; // ////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); ////Static Class Customer.PrintFullName(); OutPut:

110 110 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //////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;

111 111 P a g e // (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); ////abstarct Class doesn't support object creation //Customer c = new Customer(); DerivedCustomer d = new DerivedCustomer(); d.printfullname(); OutPut: About interface?

112 112 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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;

113 113 P a g e 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); Customer d = new Customer(); d.name = "Madhan"; d.address = "India"; d.printname(); d.printaddress(); OutPut:

114 114 P a g e 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.

115 115 P a g e using System.Collections; using System.Collections.Generic; using System.Text; //////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); Customer d = new Customer(); //runtime compiler clubs all the methods in to single class d.printfirstname(); d.printlastname();

116 116 P a g e 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.

117 117 P a g e Abstraction Abstraction solves the problem in the design level. Abstraction is used for hiding the unwanted data and giving only relevant data. Encapsulation Encapsulation solves the problem in the implementation level. 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 Encapsulation means hiding the internal details or mechanics of how how it does it. 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.Collections; using System.Collections.Generic; using System.Text; ////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()

118 118 P a g e return FirstNumber / SecondNumber; //Data Absraction and Data Encapsulation Calculate() DivideFunction d = new DivideFunction(10, 5); try //inorder to calculate Division user needs to call Validate() and d.validate(); double dd = d.calculate(); Console.WriteLine(dd); catch (Exception ex) Console.WriteLine(ex.Message); 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.Collections; using System.Collections.Generic; using System.Text; ////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)

119 119 P a g e 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; //Data Absraction and Data Encapsulation only DivideFunction d = new DivideFunction(10, 5); try //inorder to calculate Division,now user needs to call Calculate() method //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); 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().

120 120 P a g e 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.Collections; using System.Collections.Generic; using System.Text; ////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; //Data Absraction and Data Encapsulation only DivideFunction d = new DivideFunction(10, 5); try //inorder to calculate Division,now user needs to call Calculate() method //Reducing the complexity to the end user is called as Encapsulation.

121 121 P a g e double dd = d.calculate(); Console.WriteLine(dd); catch (Exception ex) Console.WriteLine(ex.Message); 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.Collections; using System.Collections.Generic; using System.Text; //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); //Method Overloading public void Add(int a, int b)

122 122 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //Operator Overloading

123 123 P a g e //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; //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

124 124 P a g e volume = Box3.getVolume(); Console.WriteLine("Volume of Box3 : 0", volume); 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.Collections; using System.Collections.Generic; using System.Text; ////Method Overriding //Same method signature in both base and derived class is called as Method Overriding class Employee public virtual void GetSalary()

125 125 P a g e Console.WriteLine("Employee Salary"); class ParminentEmployee:Employee public override void GetSalary() Console.WriteLine("Perminent Employee Salary"); //////Method Overriding ParminentEmployee p = new ParminentEmployee(); p.getsalary(); 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#.

126 126 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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 ; string yearlysalary; and class PartTimeEmployee string fname; string lname; string ; string hourlysalary; //Common code vailable for FT and PT employees so we can build common Class Employye //Move all the common code to Employee class and reuse those fields when required. class Employee public string fname;

127 127 P a g e public string lname; public string ; class FullTimeEmployee:Employee public double yearlysalary; public void PrintFullName() Console.WriteLine("Full Name:"+fname+" "+lname); class PartTimeEmployee : Employee public double hourlysalary; //////Inheritance FullTimeEmployee fte = new FullTimeEmployee(); fte.fname = "Madhan"; fte.lname = "Mamidala"; fte. = "madhanmamidala@knackhook.com"; fte.yearlysalary = ; fte.printfullname(); OutPut:

128 128 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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 ; class FullTimeEmployee:Employee public double yearlysalary; public void PrintFullName() Console.WriteLine("Full Name:"+fname+" "+lname);

129 129 P a g e //////Single Inheritance FullTimeEmployee fte = new FullTimeEmployee(); fte.fname = "Madhan"; fte.lname = "Mamidala"; fte. = "madhanmamidala@knackhook.com"; fte.yearlysalary = ; fte.printfullname(); 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

130 130 P a g e using System.Collections; using System.Collections.Generic; using System.Text; //// 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 ; 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);

131 131 P a g e //////Multilevel Inheritance EmployeeOfTheYear fte = new EmployeeOfTheYear(); fte.fname = "Madhan"; fte.lname = "Mamidala"; fte. = "madhanmamidala@knackhook.com"; fte.yearlysalary = ; fte.natureofwork = "Developer"; fte.achievements = "Completed all task in time"; fte.employeeachievements(); 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.Collections; using System.Collections.Generic; using System.Text; ////// 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.

132 132 P a g e //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 //////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(); OutPut:

133 133 P a g e About multiple inheritance through interfaces? using System.Collections; using System.Collections.Generic; using System.Text; ////// 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"); ////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(); OutPut:

134 134 P a g e About multiple interface with one class and one interface? using System.Collections; using System.Collections.Generic; using System.Text; //// 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"); //////Multiple Inheritance with 1 class and 1 Interface MyDerivedClass myclass = new MyDerivedClass(); myclass.add(); ((Interface2)myclass).Add();

135 135 P a g e OutPut: About Extension Method? using System.Collections; using System.Collections.Generic; using System.Text; //////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); //////Extension Methods int x = 3; Console.WriteLine(x.factorial()); OutPut:

136 136 P a g e 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 twodimensional array. using System.Collections; using System.Collections.Generic; using System.Text; //// 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;

137 137 P a g e ////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]); 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.

138 138 P a g e 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.Collections; using System.Collections.Generic; using System.Text; ////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); ////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:

139 139 P a g e Implement general Add() method to handle both integer and double or any other data types. using System.Collections; using System.Collections.Generic; using System.Text; ////Add method with object data type Add(10, 20); Add(10.10, 20.20); //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.

140 140 P a g e using System.Collections; using System.Collections.Generic; using System.Text; ////Generic Methods Add(10, 20); Add(10.10, 20.20); //or Add<int>(10, 20); Add<double>(10.10, 20.20); //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

141 141 P a g e 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.Collections; using System.Collections.Generic; using System.Text; ////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); //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:

142 142 P a g e 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.Collections; using System.Collections.Generic; using System.Text;

143 143 P a g e 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) operation"); Console.WriteLine("Hey man,please enter only numbers for Division 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

144 144 P a g e OutPut: About dynamic, object and var keywords? 1.When were they introduced var was introduced in C# 3.0 dynamic was introduced in C# 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

145 145 P a g e 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.Collections; using System.Collections.Generic; using System.Text; //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.

146 146 P a g e 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:

147 147 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. 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);

148 148 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. //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)

149 149 P a g e Console.WriteLine(x); 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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.

150 150 P a g e //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); 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

151 151 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. //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); OutPut: LINQ with TakeWhile?

152 152 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. //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); OutPut: LINQ with Skip?

153 153 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. //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); OutPut:

154 154 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. ////OrderBy string[] words = "cherry", "apple", "blueberry" ; var sortedwords = from w in words orderby w

155 155 P a g e 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); 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.

156 156 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. //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); OutPut:

157 157 P a g e LINQ with Distinct? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. //Distinct int[] factors = 2, 2, 3, 5, 5 ; var uniquefactors = factors.distinct(); Console.WriteLine("factors:"); foreach (var f in uniquefactors) Console.WriteLine(f); OutPut:

158 158 P a g e LINQ with Union? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. //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); OutPut:

159 159 P a g e LINQ with intersect? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. ////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);

160 160 P a g e OutPut: LINQ with Except? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. //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); OutPut:

161 161 P a g e LINQ with First? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. ///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); OutPut:

162 162 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. //FirstOrDefault int[] numbers = 1, 2, 3 ; int firstnumordefault = numbers.firstordefault(); Console.WriteLine(firstNumOrDefault);

163 163 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. ////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);

164 164 P a g e OutPut: LINQ with Count? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. ////Count int[] factors = 2, 2, 3, 5, 5 ; int uniquefactors = factors.distinct().count(); Console.WriteLine("There are 0 unique factors", uniquefactors); OutPut:

165 165 P a g e LINQ with Sum? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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. //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); OutPut: LINQ with Min, Max and Average? using System.Collections; using System.Collections.Generic;

166 166 P a g e using System.Text; using System.Linq; //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. //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); //Max int maxnum = numbers.max(); Console.WriteLine("The maximum number is 0.", maxnum); //Average double averagenum = numbers.average(); Console.WriteLine("The average number is 0.", averagenum); OutPut:

167 167 P a g e LINQ with Join? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //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; ////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 ProductName="Cola", CategoryID=001, new ProductName="Tea", CategoryID=001, new ProductName="Mustard", CategoryID=002, new ProductName="Pickles", CategoryID=002, new ProductName="Carrots", CategoryID=003, new ProductName="Bok Choy", CategoryID=003, new ProductName="Peaches", CategoryID=005, new ProductName="Melons", CategoryID=005, ;

168 168 P a g e 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,-101", item.product, item.category); Console.WriteLine(System.Environment.NewLine); OutPut: About Delegate? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq;

169 169 P a g e //Delegate acts as a function pointer which helps us to call method. //Declare a delagate public delegate void PrintDelegate(string str); //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"); public static void Print(string str) Console.WriteLine(str); OutPut: About Multicast Delegate or chaining delegates? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //Multi-cast Delegate helps to call multiple methods with single delegate. //Declare a delagate public delegate void SampleDelegate();

170 170 P a g e 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(); 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:

171 171 P a g e About Asynchronous Method call with Delegates? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; //Asynchronous Method call-executing multiple methods at same time is called as Asynchronous Method calling. //Declare a delagate public delegate void SampleDelegate_Async(); 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); public static void M1()

172 172 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; //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(); ////Asynchronous Method Calling with return value

173 173 P a g e 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");

174 174 P a g e 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;

175 175 P a g e del.endinvoke(async); //make use of the state object. string msg = (string)async.asyncstate; Console.WriteLine("Text is: 0", msg); OutPut:

176 176 P a g e About Anonymous method call? using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; //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); SampleDelegate_Anonymous del1 = delegate int a = 10; int b = 20; ; del1(); Console.WriteLine("Sume of 2 numbers is:0", a + b); 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);

177 177 P a g e 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.

178 178 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; //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"); Type t = typeof(test);

179 179 P a g e 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);

180 180 P a g e //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?

181 181 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; //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. _ //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

182 182 P a g e 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 = ParameterizedThreadStart pt = new ParameterizedThreadStart(p.EvenNumbers); Thread t1 = new Thread(pt); t1.start(target); ////Alternative way to send parameters to method Program p1 = new Program(); Console.WriteLine("Enter range value"); object target1 = Thread t2 = new Thread(p1.EvenNumbers); //Needs to comment below Even Numbers method. t2.start(target); //Main Thread and Child thread execution Program p2 = new Program(); Console.WriteLine("Main Thread Started"); Thread T3 = new Thread(Method1); T3.Start();

183 183 P a g e Thread T2 = new Thread(Method2); T2.Start(); Console.WriteLine("Main Thread Completed"); 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:

184 184 P a g e 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.

185 185 P a g e 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.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; //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. _ //Non-background thread //Thread t = new Thread(myFun); //t.name = "Thread1"; //t.isbackground = false; //t.start(); //Console.WriteLine("Main thread Running"); //// ////background thread Thread t = new Thread(myFun); t.name = "Thread1"; t.isbackground = true; t.start(); Console.WriteLine("Main thread Running");

186 186 P a g e 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.Collections; using System.Collections.Generic;

187 187 P a g e using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; //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. _ milliseconds. //threading life cycle //sleep:suspends the current thread for the specified number of Thread objthread1 = new Thread(Method1); Thread objthread2 = new Thread(Method2); ////start the thread objthread1.start(); Thread.Sleep(2000); objthread2.start(); // //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(); static void Method1() for (int i = 0; i <= 10; i++) Console.WriteLine("Method One Executed " + i.tostring());

188 188 P a g e static void Method2() for (int i = 0; i <= 10; i++) Console.WriteLine("Method Two Executed " + i.tostring()); OutPut:

189 189 P a g e 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.

190 190 P a g e 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.Collections;

191 191 P a g e using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; //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");

192 192 P a g e //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

193 193 P a g e 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!");

194 194 P a g e 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"); WindowsPhone_Lumia710 wp710 = new WindowsPhone_Lumia710(); wp710.brand(); wp710.call(); wp710.color(); wp710.launchdate(); wp710.price(); wp710.sms(); wp710.wifi(); OutPut: Incase of abstract class

195 195 P a g e 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.

196 196 P a g e Interfaces are useful when you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces. using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading; //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

197 197 P a g e //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");

198 198 P a g e //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");

199 199 P a g e 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();

200 200 P a g e 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()

201 201 P a g e 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

202 202 P a g e ////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");

203 203 P a g e 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

204 204 P a g e 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"); WindowsPhone_Lumia710 wp710 = new WindowsPhone_Lumia710(); //wp710.brand();

205 205 P a g e //wp710.call(); //wp710.color(); //wp710.launchdate(); //wp710.price(); //wp710.sms(); //wp710.wifi(); Can an interface inherit from another interface? Answer:Yes 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; interface IA void Print(); interface IB:IA void Show(); class MyClass:IB public void Show() Console.WriteLine("IA"); public void Print() Console.WriteLine("IB");

206 206 P a g e MyClass m = new MyClass(); m.print(); m.show(); 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.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; //partial interface partial interface IA void Print(); partial interface IA void Show(); class MyClass:IA

207 207 P a g e 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); MyClass m = new MyClass(); m.print();

208 208 P a g e m.show(); MyStruct s = new MyStruct(); s.m1(); s.m2(); 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?

209 209 P a g e 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.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; 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");

210 210 P a g e //when we make a call for static class methods automatically static constructor will get execute. MyClass.Show(); MyClass.Print(); 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.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; class MyClass private MyClass() Console.WriteLine("Constructor"); public void Show() Console.WriteLine("Show"); public void Print() Console.WriteLine("Print");

211 211 P a g e //Not allow to create instance of a MyClass MyClass m = new MyClass(); 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.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; 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()

212 212 P a g e Console.WriteLine("Child class Constructor"); MyChildClass m = new MyChildClass(); 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.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; class MyBaseClass public MyBaseClass() Console.WriteLine("Base class Constructor");

213 213 P a g e public void Show() Console.WriteLine("Show"); public void Print() Console.WriteLine("Print"); class MyChildClass : MyBaseClass public MyChildClass() Console.WriteLine("Child class Constructor"); MyChildClass m = new MyChildClass(); OutPut: Can you mark static constructor with access modifiers? No, we cannot use access modifiers on static constructor. using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Reflection; using System.Threading;

214 214 P a g e using System.Data.SqlClient; 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"); //when we make a call for static class methods automatically static constructor will get execute. MyClass.Show(); MyClass.Print(); OutPut: Can you have parameters for static constructors? No, static constructors cannot have parameters.

215 215 P a g e 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; 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"); //when we make a call for static class methods automatically static constructor will get execute. MyClass.Show(); MyClass.Print(); OutPut:

216 216 P a g e 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.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; SayHi(); public static void SayHi()

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio Introduction XXV Part I: C# Fundamentals 1 Chapter 1: The.NET Framework 3 What s the.net Framework? 3 Common Language Runtime 3.NET Framework Class Library 4 Assemblies and the Microsoft Intermediate Language

More information

.Net Technologies. Components of.net Framework

.Net Technologies. Components of.net Framework .Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.

More information

C#: framework overview and in-the-small features

C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Introduce C# as Object Oriented programming language. Explain, tokens,

Introduce C# as Object Oriented programming language. Explain, tokens, Module 2 98 Assignment 1 Introduce C# as Object Oriented programming language. Explain, tokens, lexicals and control flow constructs. 99 The C# Family Tree C Platform Independence C++ Object Orientation

More information

Darshan Institute of Engineering & Technology for Diploma Studies

Darshan Institute of Engineering & Technology for Diploma Studies Overview of Microsoft.Net Framework: The Dot Net or.net is a technology that is an outcome of Microsoft s new strategy to develop window based robust applications and rich web applications and to keep

More information

.Net. Course Content ASP.NET

.Net. Course Content ASP.NET .Net Course Content ASP.NET INTRO TO WEB TECHNOLOGIES HTML ü Client side scripting langs ü lls Architecture ASP.NET INTRODUCTION ü What is ASP.NET ü Image Technique and code behind technique SERVER SIDE

More information

DOT NET Syllabus (6 Months)

DOT NET Syllabus (6 Months) DOT NET Syllabus (6 Months) THE COMMON LANGUAGE RUNTIME (C.L.R.) CLR Architecture and Services The.Net Intermediate Language (IL) Just- In- Time Compilation and CLS Disassembling.Net Application to IL

More information

Diploma in Microsoft.NET

Diploma in Microsoft.NET Course Duration For Microsoft.NET Training Course : 12 Weeks (Weekday Batches) Objective For Microsoft.NET Training Course : To Become a.net Programming Professional To Enable Students to Improve Placeability

More information

Microsoft. Microsoft Visual C# Step by Step. John Sharp

Microsoft. Microsoft Visual C# Step by Step. John Sharp Microsoft Microsoft Visual C#- 2010 Step by Step John Sharp Table of Contents Acknowledgments Introduction xvii xix Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 1 Welcome to

More information

1. Introduction to the Common Language Infrastructure

1. Introduction to the Common Language Infrastructure Miller-CHP1.fm Page 1 Wednesday, September 24, 2003 1:50 PM to the Common Language Infrastructure The Common Language Infrastructure (CLI) is an International Standard that is the basis for creating execution

More information

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations , 1 C#.Net VT 2009 Course Contents C# 6 hp approx. BizTalk 1,5 hp approx. No exam, but laborations Course contents Architecture Visual Studio Syntax Classes Forms Class Libraries Inheritance Other C# essentials

More information

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 2 Computer programming: creating a sequence of instructions to enable the computer to do something Programmers do not use machine language when creating computer programs. Instead, programmers tend to

More information

MCSA Universal Windows Platform. A Success Guide to Prepare- Programming in C# edusum.com

MCSA Universal Windows Platform. A Success Guide to Prepare- Programming in C# edusum.com 70-483 MCSA Universal Windows Platform A Success Guide to Prepare- Programming in C# edusum.com Table of Contents Introduction to 70-483 Exam on Programming in C#... 2 Microsoft 70-483 Certification Details:...

More information

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led CENTER OF KNOWLEDGE, PATH TO SUCCESS Website: PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO 2010 Course: 10550A; Duration: 5 Days; Instructor-led WHAT YOU WILL LEARN This course teaches you

More information

Module 1. An Introduction to C# Module 2. Classes and Objects. Vasundhara Sector 14-A, Plot No , Near Vaishali Metro Station,Ghaziabad

Module 1. An Introduction to C# Module 2. Classes and Objects. Vasundhara Sector 14-A, Plot No , Near Vaishali Metro Station,Ghaziabad Module 1. An Introduction to C# What is.net? What is the CLR? The FCL Primitive Types Namespaces Statements and Expressions Operators Module Module 2. Classes and Objects Constructors Reference Types Object

More information

Programming in Visual Basic with Microsoft Visual Studio 2010

Programming in Visual Basic with Microsoft Visual Studio 2010 Programming in Visual Basic with Microsoft Visual Studio 2010 Course 10550; 5 Days, Instructor-led Course Description This course teaches you Visual Basic language syntax, program structure, and implementation

More information

Question And Answer.

Question And Answer. Q.1 What would be the output of the following program? using System; namespaceifta classdatatypes static void Main(string[] args) inti; Console.WriteLine("i is not used inthis program!"); A. i is not used

More information

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class. 1. What is C#? C# (pronounced "C sharp") is a simple, modern, object oriented, and type safe programming language. It will immediately be familiar to C and C++ programmers. C# combines the high productivity

More information

Microsoft Visual C# Step by Step. John Sharp

Microsoft Visual C# Step by Step. John Sharp Microsoft Visual C# 2013 Step by Step John Sharp Introduction xix PART I INTRODUCING MICROSOFT VISUAL C# AND MICROSOFT VISUAL STUDIO 2013 Chapter 1 Welcome to C# 3 Beginning programming with the Visual

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

INTRODUCTION TO.NET. Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.)

INTRODUCTION TO.NET. Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.) INTRODUCTION TO.NET Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.) CLR Architecture and Services The.Net Intermediate Language (IL) Just- In-

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Dot Net Online Training

Dot Net Online Training chakraitsolutions.com http://chakraitsolutions.com/dotnet-online-training/ Dot Net Online Training DOT NET Online Training CHAKRA IT SOLUTIONS TO LEARN ABOUT OUR UNIQUE TRAINING PROCESS: Title : Dot Net

More information

UNIT 1. Introduction to Microsoft.NET framework and Basics of VB.Net

UNIT 1. Introduction to Microsoft.NET framework and Basics of VB.Net UNIT 1 Introduction to Microsoft.NET framework and Basics of VB.Net 1 SYLLABUS 1.1 Overview of Microsoft.NET Framework 1.2 The.NET Framework components 1.3 The Common Language Runtime (CLR) Environment

More information

New programming language introduced by Microsoft contained in its.net technology Uses many of the best features of C++, Java, Visual Basic, and other

New programming language introduced by Microsoft contained in its.net technology Uses many of the best features of C++, Java, Visual Basic, and other C#.NET? New programming language introduced by Microsoft contained in its.net technology Uses many of the best features of C++, Java, Visual Basic, and other OO languages. Small learning curve from either

More information

This tutorial has been prepared for the beginners to help them understand basics of c# Programming.

This tutorial has been prepared for the beginners to help them understand basics of c# Programming. About thetutorial C# is a simple, modern, general-purpose, object-oriented programming language developed by Microsoft within its.net initiative led by Anders Hejlsberg. This tutorial covers basic C# programming

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Course Syllabus C # Course Title. Who should attend? Course Description

Course Syllabus C # Course Title. Who should attend? Course Description Course Title C # Course Description C # is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the.net Framework.

More information

C# Programming in the.net Framework

C# Programming in the.net Framework 50150B - Version: 2.1 04 May 2018 C# Programming in the.net Framework C# Programming in the.net Framework 50150B - Version: 2.1 6 days Course Description: This six-day instructor-led course provides students

More information

Object-Oriented Programming in C# (VS 2015)

Object-Oriented Programming in C# (VS 2015) Object-Oriented Programming in C# (VS 2015) This thorough and comprehensive 5-day course is a practical introduction to programming in C#, utilizing the services provided by.net. This course emphasizes

More information

DOT NET SYLLABUS FOR 6 MONTHS

DOT NET SYLLABUS FOR 6 MONTHS DOT NET SYLLABUS FOR 6 MONTHS INTRODUCTION TO.NET Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.) CLR Architecture and Services The.Net Intermediate

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Object-Oriented Programming in C# (VS 2012)

Object-Oriented Programming in C# (VS 2012) Object-Oriented Programming in C# (VS 2012) This thorough and comprehensive course is a practical introduction to programming in C#, utilizing the services provided by.net. This course emphasizes the C#

More information

CHAPTER 1: INTRODUCING C# 3

CHAPTER 1: INTRODUCING C# 3 INTRODUCTION xix PART I: THE OOP LANGUAGE CHAPTER 1: INTRODUCING C# 3 What Is the.net Framework? 4 What s in the.net Framework? 4 Writing Applications Using the.net Framework 5 What Is C#? 8 Applications

More information

Programming C# 5.0. Ian Griffiths O'REILLY' Beijing Cambridge * Farnham Kbln Sebastopol Tokyo

Programming C# 5.0. Ian Griffiths O'REILLY' Beijing Cambridge * Farnham Kbln Sebastopol Tokyo Programming C# 5.0 Ian Griffiths O'REILLY' Beijing Cambridge * Farnham Kbln Sebastopol Tokyo Preface xvii 1. Introducing C# 1 Why C#? 1 Why Not C#? 3 C#'s Defining Features 5 Managed Code and the CLR 7

More information

Programming in C# for Experienced Programmers

Programming in C# for Experienced Programmers Programming in C# for Experienced Programmers Course 20483C 5 Days Instructor-led, Hands-on Introduction This five-day, instructor-led training course teaches developers the programming skills that are

More information

The C# Programming Language. Overview

The C# Programming Language. Overview The C# Programming Language Overview Microsoft's.NET Framework presents developers with unprecedented opportunities. From web applications to desktop and mobile platform applications - all can be built

More information

Introducing C# and the.net Framework

Introducing C# and the.net Framework 1 Introducing C# and the.net Framework C# is a general-purpose, type-safe, object-oriented programming language. The goal of the language is programmer productivity. To this end, the language balances

More information

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo Learning C# 3.0 Jesse Liberty and Brian MacDonald O'REILLY Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo Table of Contents Preface xv 1. C# and.net Programming 1 Installing C# Express 2 C# 3.0

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

Mastering VB.NET using Visual Studio 2010 Course Length: 5 days Price: $2,500

Mastering VB.NET using Visual Studio 2010 Course Length: 5 days Price: $2,500 Mastering VB.NET using Visual Studio 2010 Course Length: 5 days Price: $2,500 Summary Each day there will be a combination of presentations, code walk-throughs, and handson projects. The final project

More information

.NET-6Weeks Project Based Training

.NET-6Weeks Project Based Training .NET-6Weeks Project Based Training Core Topics 1. C# 2. MS.Net 3. ASP.NET 4. 1 Project MS.NET MS.NET Framework The.NET Framework - an Overview Architecture of.net Framework Types of Applications which

More information

SECURED PROGRAMMING IN.NET DETAILED TRAINING CONTENT INDUSTRIAL TRAINING PROGRAM ( )

SECURED PROGRAMMING IN.NET DETAILED TRAINING CONTENT INDUSTRIAL TRAINING PROGRAM ( ) SECURED PROGRAMMING IN.NET DETAILED TRAINING CONTENT INDUSTRIAL TRAINING PROGRAM (2013-2014) MODULE: C# PROGRAMMING CHAPTER 1: INTRODUCING.NET AND C# 1.1 INTRODUCTION TO LANGUAGES C++ C# DIFFERENCES BETWEEN

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Apex TG India Pvt. Ltd.

Apex TG India Pvt. Ltd. (Core C# Programming Constructs) Introduction of.net Framework 4.5 FEATURES OF DOTNET 4.5 CLR,CLS,CTS, MSIL COMPILER WITH TYPES ASSEMBLY WITH TYPES Basic Concepts DECISION CONSTRUCTS LOOPING SWITCH OPERATOR

More information

C# Syllabus. MS.NET Framework Introduction

C# Syllabus. MS.NET Framework Introduction C# Syllabus MS.NET Framework Introduction The.NET Framework - an Overview Framework Components Framework Versions Types of Applications which can be developed using MS.NET MS.NET Base Class Library MS.NET

More information

DOT NET COURSE BROCHURE

DOT NET COURSE BROCHURE Page 1 1Pointer Technology Chacko Towers,Anna nagar Main Road, Anna Nager(Annai Insititute 2nd Floor) Pondicherry-05 Mobile :+91-9600444787,9487662326 Website : http://www.1pointer.com/ Email : info@1pointer.com/onepointertechnology@gmail.com

More information

NET 3.0 and NET 3.0 contains four building blocks, shown in the figure below:

NET 3.0 and NET 3.0 contains four building blocks, shown in the figure below: NET 3.0 and 3.5 NET 3.0 is a brand name for a set of modern technologies, designed to be the next-generation Windows development platform..net 3.0 was released with Windows Vista in November 2006 2007..NET

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction 1. Which language is not a true object-oriented programming language? A. VB 6 B. VB.NET C. JAVA D. C++ 2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a)

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

PES INSTITUTE OF TECHNOLOGY

PES INSTITUTE OF TECHNOLOGY Seventh Semester B.E. IA Test-I, 2014 USN 1 P E I S PES INSTITUTE OF TECHNOLOGY C# solution set for T1 Answer any 5 of the Following Questions 1) What is.net? With a neat diagram explain the important

More information

Migrate Your Skills to Microsoft.NET Framework 2.0 and 3.0 using Visual Studio 2005 (C#)

Migrate Your Skills to Microsoft.NET Framework 2.0 and 3.0 using Visual Studio 2005 (C#) Migrate Your Skills to Microsoft.NET Framework 2.0 and 3.0 using Visual Studio 2005 (C#) Course Length: 5 Days Course Overview This instructor-led course teaches developers to gain in-depth guidance on

More information

DEVELOPING WEB APPLICATIONS WITH MICROSOFT VISUAL STUDIO Course: 10264A; Duration: 5 Days; Instructor-led

DEVELOPING WEB APPLICATIONS WITH MICROSOFT VISUAL STUDIO Course: 10264A; Duration: 5 Days; Instructor-led CENTER OF KNOWLEDGE, PATH TO SUCCESS Website: DEVELOPING WEB APPLICATIONS WITH MICROSOFT VISUAL STUDIO 2010 Course: 10264A; Duration: 5 Days; Instructor-led WHAT YOU WILL LEARN In this course, students

More information

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments 2 Class Keyword class used to define new type specify

More information

C # Language Specification

C # Language Specification C # Language Specification Copyright Microsoft Corporation 1999-2001. All Rights Reserved. Please send corrections, comments, and other feedback to sharp@microsoft.com Notice 1999-2001 Microsoft Corporation.

More information

Course Hours

Course Hours Programming the.net Framework 4.0/4.5 with C# 5.0 Course 70240 40 Hours Microsoft's.NET Framework presents developers with unprecedented opportunities. From 'geoscalable' web applications to desktop and

More information

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017 C++\CLI Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017 Comparison of Object Models Standard C++ Object Model All objects share a rich memory model: Static, stack, and heap Rich object life-time

More information

DIPLOMA IN PROGRAMMING WITH DOT NET TECHNOLOGIES

DIPLOMA IN PROGRAMMING WITH DOT NET TECHNOLOGIES DIPLOMA IN PROGRAMMING WITH DOT NET TECHNOLOGIES USA This training program is highly specialized training program with the duration of 72 Credit hours, where the program covers all the major areas of C#

More information

Introduction To C#.NET

Introduction To C#.NET Introduction To C#.NET Microsoft.Net was formerly known as Next Generation Windows Services(NGWS).It is a completely new platform for developing the next generation of windows/web applications. However

More information

How to be a C# ninja in 10 easy steps. Benjamin Day

How to be a C# ninja in 10 easy steps. Benjamin Day How to be a C# ninja in 10 easy steps Benjamin Day Benjamin Day Consultant, Coach, Trainer Scrum.org Classes Professional Scrum Developer (PSD) Professional Scrum Foundations (PSF) TechEd, VSLive, DevTeach,

More information

C# Programming: From Problem Analysis to Program Design. Fourth Edition

C# Programming: From Problem Analysis to Program Design. Fourth Edition C# Programming: From Problem Analysis to Program Design Fourth Edition Preface xxi INTRODUCTION TO COMPUTING AND PROGRAMMING 1 History of Computers 2 System and Application Software 4 System Software 4

More information

Fig 1.1.NET Framework Architecture Block Diagram

Fig 1.1.NET Framework Architecture Block Diagram Overview of Microsoft.NET Framework The.NET Framework is a technology that supports building and running the next generation of applications and XML Web services. Using.Net technology it is easy to use

More information

C#.Net Interview Questions

C#.Net Interview Questions 1 P a g e C#.Net Interview Questions 2 P a g e Table of Contents 1. About?... 8 2. About Write, WriteLine, Read, ReadLine and ReadKey methods?... 8 3. About difference between Decimal, Float and Double

More information

Uka Tarsadia University MCA ( 3rd Semester)/M.Sc.(CA) (1st Semester) Course : / Visual Programming Question Bank

Uka Tarsadia University MCA ( 3rd Semester)/M.Sc.(CA) (1st Semester) Course : / Visual Programming Question Bank Unit 1 Introduction to.net Platform Q: 1 Answer in short. 1. Which three main components are available in.net framework? 2. List any two new features added in.net framework 4.0 which is not available in

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

A NET Refresher

A NET Refresher .NET Refresher.NET is the latest version of the component-based architecture that Microsoft has been developing for a number of years to support its applications and operating systems. As the name suggests,.net

More information

Getting started 7. Storing values 21. Creating variables 22 Reading input 24 Employing arrays 26 Casting data types 28 Fixing constants 30 Summary 32

Getting started 7. Storing values 21. Creating variables 22 Reading input 24 Employing arrays 26 Casting data types 28 Fixing constants 30 Summary 32 Contents 1 2 3 Contents Getting started 7 Introducing C# 8 Installing Visual Studio 10 Exploring the IDE 12 Starting a Console project 14 Writing your first program 16 Following the rules 18 Summary 20

More information

10/9/2012. Sample C# program:

10/9/2012. Sample C# program: Creating and Running Your First C# Program Text Book : C# Programming From Problem Analysis to Program design, Barbara Doyle Grading : Homeworks 20% Lecture Presentation 20% Final : % 20 Project : 40%

More information

Appendix G: Writing Managed C++ Code for the.net Framework

Appendix G: Writing Managed C++ Code for the.net Framework Appendix G: Writing Managed C++ Code for the.net Framework What Is.NET?.NET is a powerful object-oriented computing platform designed by Microsoft. In addition to providing traditional software development

More information

Advanced WCF 4.0 .NET. Web Services. Contents for.net Professionals. Learn new and stay updated. Design Patterns, OOPS Principles, WCF, WPF, MVC &LINQ

Advanced WCF 4.0 .NET. Web Services. Contents for.net Professionals. Learn new and stay updated. Design Patterns, OOPS Principles, WCF, WPF, MVC &LINQ Serialization PLINQ WPF LINQ SOA Design Patterns Web Services 4.0.NET Reflection Reflection WCF MVC Microsoft Visual Studio 2010 Advanced Contents for.net Professionals Learn new and stay updated Design

More information

C# 6.0 in a nutshell / Joseph Albahari & Ben Albahari. 6th ed. Beijin [etc.], cop Spis treści

C# 6.0 in a nutshell / Joseph Albahari & Ben Albahari. 6th ed. Beijin [etc.], cop Spis treści C# 6.0 in a nutshell / Joseph Albahari & Ben Albahari. 6th ed. Beijin [etc.], cop. 2016 Spis treści Preface xi 1. Introducing C# and the.net Framework 1 Object Orientation 1 Type Safety 2 Memory Management

More information

Microsoft.NET Programming (C#, ASP.NET,ADO.NET, VB.NET, Crystal Report, Sql Server) Goal: Make the learner proficient in the usage of MS Technologies

Microsoft.NET Programming (C#, ASP.NET,ADO.NET, VB.NET, Crystal Report, Sql Server) Goal: Make the learner proficient in the usage of MS Technologies Microsoft.NET Programming (C#, ASP.NET,ADO.NET, VB.NET, Crystal Report, Sql Server) Goal: Make the learner proficient in the usage of MS Technologies for web applications development using ASP.NET, XML,

More information

10266 Programming in C Sharp with Microsoft Visual Studio 2010

10266 Programming in C Sharp with Microsoft Visual Studio 2010 10266 Programming in C Sharp with Microsoft Visual Studio 2010 Course Number: 10266A Category: Visual Studio 2010 Duration: 5 days Course Description The course focuses on C# program structure, language

More information

Department of Computer Applications

Department of Computer Applications MCA 512:.NET framework and C# [Part I : Medium Answer type Questions] Unit - 1 Q1. What different tools are available and used to develop.net Applications? Hint a).net Framework SDK b) ASP.NET Web Matrix

More information

Visual C# 2008 How to Program, 3/E Outline

Visual C# 2008 How to Program, 3/E Outline vcsharp2008htp_outline.fm Page ix Monday, December 17, 2007 4:39 PM Visual C# 2008 How to Program, 3/E Outline ( subject to change) current as of 12/17/07. As the contents change, we ll post updates at

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Creating and Running Your First C# Program

Creating and Running Your First C# Program Creating and Running Your First C# Program : http://eembdersler.wordpress.com Choose the EEE-425Programming Languages (Fall) Textbook reading schedule Pdf lecture notes Updated class syllabus Midterm and

More information

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 Creating and Running Your First C# Program : http://eembdersler.wordpress.com Choose the EEE-425Programming Languages (Fall) Textbook reading schedule Pdf lecture notes Updated class syllabus Midterm and

More information

Table of Contents Preface Bare Necessities... 17

Table of Contents Preface Bare Necessities... 17 Table of Contents Preface... 13 What this book is about?... 13 Who is this book for?... 14 What to read next?... 14 Personages... 14 Style conventions... 15 More information... 15 Bare Necessities... 17

More information

.Net Interview Questions

.Net Interview Questions .Net Interview Questions 1.What is.net? NET is an integral part of many applications running on Windows and provides common functionality for those applications to run. This download is for people who

More information

C#.NET TRAINING / /

C#.NET TRAINING / / C#.NET TRAINING.NET ENTERPRISE ARCHITECTURE Introduction to the.net platform Common Language Run Time(CLR) The Common Type Specification(CTS) The Common Language Specification(CLS) Microsoft Intermediate

More information

Developing Microsoft.NET Applications for Windows (Visual Basic.NET)

Developing Microsoft.NET Applications for Windows (Visual Basic.NET) Developing Microsoft.NET Applications for Windows (Visual Basic.NET) Course Number: 2555 Length: 1 Day(s) Certification Exam This course will help you prepare for the following Microsoft Certified Professional

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.5: Methods A Deeper Look Xianrong (Shawn) Zheng Spring 2017 1 Outline static Methods, static Variables, and Class Math Methods with Multiple

More information

Saikat Banerjee Page 1

Saikat Banerjee Page 1 1.What is.net? NET is an integral part of many applications running on Windows and provides common functionality for those applications to run. This download is for people who need.net to run an application

More information

Unit 1: Visual Basic.NET and the.net Framework

Unit 1: Visual Basic.NET and the.net Framework 1 Chapter1: Visual Basic.NET and the.net Framework Unit 1: Visual Basic.NET and the.net Framework Contents Introduction to.net framework Features Common Language Runtime (CLR) Framework Class Library(FCL)

More information

10267A CS: Developing Web Applications Using Microsoft Visual Studio 2010

10267A CS: Developing Web Applications Using Microsoft Visual Studio 2010 10267A CS: Developing Web Applications Using Microsoft Visual Studio 2010 Course Overview This instructor-led course provides knowledge and skills on developing Web applications by using Microsoft Visual

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Prerequisites: The student should have programming experience in a high-level language. ITCourseware, LLC Page 1. Object-Oriented Programming in C#

Prerequisites: The student should have programming experience in a high-level language. ITCourseware, LLC Page 1. Object-Oriented Programming in C# Microsoft s.net is a revolutionary advance in programming technology that greatly simplifies application development and is a good match for the emerging paradigm of Web-based services, as opposed to proprietary

More information

Variable Scope The Main() Function Struct Functions Overloading Functions Using Delegates Chapter 7: Debugging and Error Handling Debugging in Visual

Variable Scope The Main() Function Struct Functions Overloading Functions Using Delegates Chapter 7: Debugging and Error Handling Debugging in Visual Table of Contents Title Page Introduction Who This Book Is For What This Book Covers How This Book Is Structured What You Need to Use This Book Conventions Source Code Errata p2p.wrox.com Part I: The OOP

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Unit-II Programming and Problem Solving (BE1/4 CSE-2) Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite

More information

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries 1 CONTENTS 1. Introduction to Java 2. Holding Data 3. Controllin g the f l o w 4. Object Oriented Programming Concepts 5. Inheritance & Packaging 6. Handling Error/Exceptions 7. Handling Strings 8. Threads

More information

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1 CSE P 501 Compilers Java Implementation JVMs, JITs &c Hal Perkins Winter 2008 3/11/2008 2002-08 Hal Perkins & UW CSE V-1 Agenda Java virtual machine architecture.class files Class loading Execution engines

More information

10264A CS: Developing Web Applications with Microsoft Visual Studio 2010

10264A CS: Developing Web Applications with Microsoft Visual Studio 2010 10264A CS: Developing Web Applications with Microsoft Visual Studio 2010 Course Number: 10264A Course Length: 5 Days Course Overview In this course, students will learn to develop advanced ASP.NET MVC

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Introduction to Microsoft.NET Programming Using Microsoft Visual Studio 2008 (C#) Course Overview. Prerequisites. Audience.

Introduction to Microsoft.NET Programming Using Microsoft Visual Studio 2008 (C#) Course Overview. Prerequisites. Audience. Introduction to Microsoft.NET Programming Using Microsoft Visual Studio 2008 (C#) Course Number: 6368A Course Length: 1 Day Course Overview This instructor-led course provides an introduction to developing

More information

A Comparison of Visual Basic.NET and C#

A Comparison of Visual Basic.NET and C# Appendix B A Comparison of Visual Basic.NET and C# A NUMBER OF LANGUAGES work with the.net Framework. Microsoft is releasing the following four languages with its Visual Studio.NET product: C#, Visual

More information

DC69 C# &.NET JUNE C# is a simple, modern, object oriented language derived from C++ and Java.

DC69 C# &.NET JUNE C# is a simple, modern, object oriented language derived from C++ and Java. Q.2 a. What is C#? Discuss its features in brief. 1. C# is a simple, modern, object oriented language derived from C++ and Java. 2. It aims to combine the high productivity of Visual Basic and the raw

More information