text: Learning the Basics of C#
  In simple terms, programming is the art of writing a set of commands that instruct a computer to execute a particular task. In the early days, programming capabilities were limited due to memory and speed restrictions. Due to this, programmers wrote crude and simple tasks that did elementary jobs. With time and with more enhancements, people started writing programs in procedural languages such as COBOL.
  Although the languages did the work, the programs had some limitations. There was not much scope for writing reusable components or design patterns that could be used in different places in the application. Hence, the applications were difficult to maintain and scalability was a challenge.
  As a result, efforts were made to develop high-level programming languages that could overcome all such challenges faced by procedural languages. With time, many different programming languages were devised. C was developed between 1972 and 1973. At the time, it was a low-level procedural language that depended upon the underlying platform, such as Linux or Windows. C also did not fully utilize the concept of object-oriented programming (which we will go through in Chapter 3, Understanding Object-Oriented Programming).
  C++ was introduced in 1998, and provided programmers with the ability to effectively use the concepts of object-oriented programming while still retaining the machine-level programming features provided by C. In this book, we will go through the different aspects of programming in C#. While retaining the OOP capabilities of C++, C# allows us to write programs independent of the underlying hardware implementation.
  In this chapter, we will go over the basics of C#. We will review its underlying fundamentals and dive deep into the .NET Framework architecture. We will learn how common language runtime works to translate the application code to machine-level code. We will learn how C# is both different and similar to other languages, such as C and C++. We will then learn about the different components in a C# program, such as classes, namespaces, and assemblies. And, as a common tradition for any new language, we will look at the implementation of a Hello World program.
  This chapter consists of the following topics:
  - Comparing C# with C and C++
  - .NET Framework
  - .NET Framework release versions
  - Visual Studio for C#
  - Basic structure of C#
  - Creating a basic program in C#
  Technical requirements
  For a better understanding of the chapter, you require the following knowledge:
  - A basic understanding of software development
  - A basic understanding of common programming languages: C, C++ and C#
  For the entirety of this book, we will be going through different code examples in C# and will be using Visual Studio 2017 Community Edition for the code examples. The following hardware requirements are essential for Visual Studio:
  - Operating system:
  - Windows 10 or higher
  - Windows Server 2016: Standard and Datacenter
  - Windows 8.1
  - Windows Server 2012 R2: Essential, Standard, and Datacenter
  - Windows 7 SP1
  - Hardware requirements:
  - Minimum 2 GB of RAM
  - 1.8 GHz or faster processor
  - Additional requirements:
  - Administrative rights of the system
  - .NET Framework 4.5
  - Visual Studio: All code examples in this book have been compiled on Visual Studio Community Edition 2017. It's available for installation at:.
  Sample code for this chapter can be found on GitHub at.
  Comparing C# with C and C++
  In this section, we will explore how C# compares against other programming languages, such as C and C++. We will look at aspects that make C# similar, and also areas in which it differs from these languages.
  C# versus C
  If you have done some previous development on C# and C , you will realize that they follow similar code syntax, such as the use of semi-colons, and similar declarations of methods; the two languages are very different from one another. Just like in C, we can declare data variables with the same type, such as Char, and Integer. The following features make C# different from C:
  Let's now look at how C# compares against another language, C++. After exploring the comparison between C# and C++, we will also explore how the .NET Framework makes C# a platform-independent language compared to C and C++.
  C# versus C++
  In most programming scenarios, C++ can be classified as an extension of C and can execute all the code that was written in C. It provides all the features of object-oriented programming while retaining the functionalities provided by C. There are several features that are common between C# and C++. Just as in C#, we can implement object-oriented programming, exception handling, and type safety in C++. However, there are also certain things that make C# different to C++ and more similar to Java.
  Before we look at the differences and similarities between C# and C++, we must understand some key concepts pertaining to object-oriented programming.
  The languages that implement object-oriented programming are classified in two categories:
  - Fully object-oriented languages
  - Pure object-oriented languages
  A language is classified as a fully object-oriented programming language if it implements at least the four core pillars of Abstraction, Encapsulation, Polymorphism, and Inheritance.
  On the other hand, a language can be defined as a pure object-oriented programming language when, apart from being fully object-oriented programming, it only contains classes and objects. This means that all methods, properties, and attributes declared must be inside a class and also should not have any predefined data types, such as char and int.
  In the case of C#, we can have predefined data types. In Chapter 2, Understanding Classes, Structures, and Interfaces, we will look into those predefined data types in detail. This makes C# a fully object-oriented language and not a pure object-oriented language.
  On the other hand, in the case of C++, we can define methods that are not part of any class. This, too, makes it a fully object-oriented language.
  Now, let's look at some of the similarities and differences between C# and C++:
  In the previous two sections, we saw how C# compares to both C and C++. However, there is one important difference that we haven't yet explored. That feature is platform independence and was one of the main reasons C# was introduced by Microsoft. When working with C and C++, we need to compile the code in accordance with the underlying platform features, such as the operating system.
  Suppose we write an application in C or C++ and compile it. During the compilation stage, the compiler translates the code into a native language code that is only compatible with the underlying platform. This basically implies that an application in C++, developed and compiled on a Windows machine, will just be compatible with a Windows machine. If the compiled bits are used on a different system, such as Linux, it will not work there.
  This difference is caused due to the varying nature of compilers and their compatibility with underlying operating systems, such as Linux and Windows. These are some of the common compilers in Linux and Windows that are available for C and C++:
  - Linux: GCC, Failsafe C, and SubC
  - Windows: Microsoft Windows SDK, Turbo C++, and SubC
  Before C# was developed, this platform dependence issue was a major disadvantage compared to some of the other programming languages, such as Java. In Java, when an application is compiled, it's not directly converted into machine code. Instead, it's converted into an intermediate language known as ByteCode. The ByteCode is platform-independent and can be deployed on different platforms.
  When Microsoft introduced C#, they inculcated the same principle in the language. When an application written in C# is compiled, instead of being converted to the native code compatible with the machine, the application is first translated to an intermediate language commonly known as IL code.
  After the IL code is generated, the Common Language Runtime (CLR) comes into effect. CLR is a runtime environment that sits in the memory of the underlying machine and converts the IL code to the native code, which is specific to the machine. This process is Just-In-Time (JIT) compilation. In the next section, we will look at the underlying platform of the .NET Framework, which handles all this for a C# application.
  .NET Framework
  .NET Framework is a software development framework on which we can write a number of languages such as C#, ASP.NET, C++, Python, Visual Basic, and F#.
  .NET Framework provides language interoperability across different programming languages. Applications written in .NET Framework execute in an environment or a virtual machine component known as CLR.
  The following diagram illustrates the different components in .NET Framework:
  In the previous diagram, note the following:
  - At the top of the hierarchy, we have applications or the program code that we write in .NET. It could be as simple as a Hello World console application program, which we will create in this chapter, or as complex as writing multi-threaded applications.
  - The applications are based upon a set of classes or design templates, which constitutes a class library.
  - The code written in these applications is then acted upon by CLR, which makes use of the Just in Time (JIT) compiler to convert the application code into machine code.
  - The machine code is specific to the underlying platform properties. So, for different systems, such as Linux or Windows, it will be different.
  In the next section, we will the .NET Framework in detail learn how interact with each other.
  Languages/applications
  Languages indicate the different types of applications that can be built in .NET Framework. If you are new to .NET Framework, you may not be familiar with some of the applications listed here:
  - ADO.NET: In an ADO.NET application, we write programs to access data from sources such as SQL Server, OLE DB, and XML sources.
  - ASP.NET: In an ASP.NET application, we write programs to build web apps such as websites and services using C#, HTML, CSS, and so on.
  - CORE: In .NET Core applications, we write programs that support cross-platform functionality. The programs could be web apps, console applications, or libraries.
  - Windows Forms: In Windows Forms applications, we write programs that provide client-side applications for desktops, tablets, and mobile devices.
  - WPF: In WPF or Windows Presentation Foundation, we write programs that provide user interfaces in Windows-based applications. It runs only on Windows-supported platforms, such as Windows 10, Windows Server 2019, and Windows Vista.
  - WCF: In WCF or Windows Communication Foundation, we write programs that provide a set of APIs, or in simpler terms, services, to exchange data between two distinct systems.
  - LINQ: In LINQ, we write programs that provide data querying capabilities on .NET applications.
  - Parallel FX: In Parallel FX, we write programs that support parallel programming. It involves writing programs that utilize the CPU's capabilities to the fullest by executing several threads in parallel to complete a task.
  The class library
  The class library in .NET Framework consists of a collection of interfaces, classes, and value types on which the applications are built.
  These collections are organized in different containers known as namespaces. They are a set of standard class libraries that can be used for different purposes in an application. Here are some of the namespaces:
  - Microsoft.Sharp: This contains a type that supports compilation and code generation for C# source code, and the type that supports conversion between Dynamic Language Runtime and C#.
  - Microsoft.Jscript: This contains classes that support compilation and code generation using JavaScript.
  - Microsoft.VisualBasic: This contains classes that support compilation and code generation for Visual Basic.
  - Microsoft.VisualC: This contains classes that support compilation and code generation for Visual C++.
  Common Language Runtime (CLR)
  CLR is a runtime environment that sits in the memory of the underlying machine and converts the IL code to native code. The native code is specific to the underlying platform in which the code is running. This provides a platform independence feature in a typical application made on .NET Framework. Some of the other features provided by CLR are mentioned here:
  - Memory management: CLR provides automatic allocation and release of memory across the application. Due to this, developers do not need to explicitly write code to manage memory. This eliminates issues that can lead to degradation of application performance due to memory leaks. CLR manages the allocation and removal of memory using a garbage collector, which manages the memory allocation in the following manner:
  - Allocating memory: When an application is executed in CLR, it reserves a continuous space of memory for its execution. The reserved space is known as a managed heap. The heap maintains a pointer to the memory address where the next object defined in the process will be allocated.
  - Releasing memory: During the runtime execution of the program, the garbage collector runs at scheduled times and examines whether the memory allocated in heaps are still in scope of program execution or not.
  - It determines whether the program is still using the memory on the basis of roots or the collection of memory objects are still in the scope of the program. If any memory allocation is not reachable as per the collection in the root, the garbage collector determines that the memory allocated in that memory space can be released.
  - We will look into memory management in detail in Chapter 9, Manage the Object Life Cycle.
  - Exception handling: When an application is being executed, it may result in certain execution paths that could generate some errors in the application. Some of the common examples are as follows:
  - When an application tries to access an object such as a file that is not present in the specified directory path.
  - When an application tries to execute a query on the database but the connection between the application and the underlying database is broken/not open.
  - We will look into exception handling in detail when we go through Chapter 7, Implementing Exception Handling.
  In the next section, we will look at the release history of .NET Framework and its compatibility with different versions of CLR and C#.
  .NET Framework release versions
  The first version of .NET Framework 1.0 was released in 2002. Just like .NET Framework, there are different versions of CLR and C# as well. The different versions of .NET Framework are compatible with some particular versions of both CLR and C#. The following table provides a compatibility mapping between the different .NET Framework versions and its compatible versions of CLR:
  The following table matches the different versions of .NET Framework with its compatible C# version, and lists some of the important programming features that were released in that version of C#:
  In the next section, we will look at Visual Studio, an IDE tool provided by Microsoft for building applications with .NET Framework, and some of its built-in features that can help us during the development phase.
  Visual Studio for C#
  Microsoft Visual Studio is an Integrated Development Environment (IDE) tool used by developers worldwide to develop, compile, and execute their .NET Framework applications. There are several features provided in the tool that help developers not only improve the quality of the application developed, but also greatly reduce the time of development.
  Some of the key features of Visual Studio are mentioned here:
  - It uses Microsoft software development platforms such as Windows API, Forms, WPF, and Silverlight.
  - While writing code, it provides IntelliSense code-completion features, which help the developers write code efficiently.
  - It also provides a forms designer for building GUI applications, a class designer, and database schema designer.
  - It provides support for different source control systems, such as GitHub and TFS.
  The current version of Visual Studio is 2017. For development purposes, Microsoft provides a Community Edition of Visual Studio, which is free of cost and can be used for non-commercial activities.
  It's essential that before using the Community Edition, we go through the terms and conditions of use as well:.
  In the next section, we will do a walk-through on the basic syntax involved in writing a basic C# application.
  Basic structure of C#
  In this section, we will go over a basic programming syntax of a C# application, namely: classes, namespaces, and assemblies..
  As an example, we will look at the representation of a car as an object in C#. At a very basic level, a car will have attributes such as the following:
  - Make: For example Toyota, Ford, or Honda.
  - Model: For example Mustang, Focus, or Beetle.
  - Color: Color of the car, such as Red or Black.
  - Mileage: Distance covered per liter of fuel consumed.
  Please note that a car can have more attributes, but as this example is just being used for the sake of explanation, we have included these basic attributes. While writing a C# application, all of these will be captured as attributes for the Car class.
  Similarly, to make sure the Car class achieves all of the desired features, it will need to implement the following operations:
  - StartEngine: This function represents how the car starts moving.
  - GainSpeed: This function represents how the car accelerates.
  - ApplyBrake: This function represents how the car applies brakes to slow down.
  - StopEngine: This function represents how the car stops.
  While writing any application in C#, the starting point is always to capture all the actors/objects that are interacting with each other. Once we identify the actors, we can then identify the data attributes and methods that each of them must have so that they can exchange the required information with each other.
  For the Car example being discussed, the following would be the definition of the Car class. For the sake of explanation, we have just assumed that the attributes will be of type String; however, when we go through Chapter 2, Understanding Classes, Structures, and Interfaces, we will go over some more data types that can be declared in a class. For the car example, the following syntax would be a representative program in a C# application:
  class Car
  {
  string Make;
  string Model;
  string Color;
  float Mileage;
  void StartEngine()
  {
  // Implement Start Engine.
  }
  void GainSpeed()
  {
  // Implement Gain Speed.
  }
  void ApplyBrake()
  {
  // Implement Gain Speed.
  }
  void StopEngine()
  {
  // Implement Gain Speed.
  }
  }
  In any application, there can be some classes that are related to one another. They can be based in terms of similar functionality, or they could be dependent on each other. In C#, we handle such a segregation of functionality via namespaces. For example, we can have a namespace for handling all operations related to reading/writing logs in the file directory. Similarly, we can have namespaces for handling all operations related to capturing user-specified information from inputs.
  When our applications continue to evolve and we have several namespaces, we may have a need to group related namespaces under one umbrella. This ensures that if any class changes under any particular namespaces, it will not affect all the classes defined in the application. This structuring of namespace is done via assemblies in C#. Assemblies are also known as DLLs, or dynamically linked libraries. Depending upon how we structure our code, when an application is compiled, it results in multiple DLLs.
  Creating a basic program in C#
  Now we will look at how to create a basic program in C#. For the sake of explanation, we will work on the Console Application project:
  - To create a new project, click on File | New Project and select Console App (.NET Framework) as the project type:
  After giving the solution an appropriate name and path, click on OK. Check that the solution has been created. At this point, you should see the Solution Explorer. By default, a .cs file, Program.cs, should be added to the solution. By default, a method by the name of Main will also be added to the class. This method is the first entry point when this application is executed.
  - Let's open Program.cs at this stage. By default, the project will have the following using expressions for the following namespaces:
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  A using statement basically signifies that the program can use the classes and methods defined in those namespaces for any execution. In further chapters, we will go over namespaces in detail and learn how to use them.
  - Now, have a look at the program structure. By default, each class needs to be associated with a namespace. The namespace expression present in the Program.cs class indicates the namespace this class is part of:
  Each method in C# consists of two parts:
  - Input parameters: This is a list of variables that will be passed to the function when it's executed.
  - Return type: This is the value that will be returned by the function to the caller when the function finishes its processing.
  In the case of the Program function declared previously, the input variable is a collection of arguments. The output variable is void; in other words, it does not return anything. In the forthcoming chapters, we will go over functions in more detail.
  Now, let's write a program syntax to execute the famous Hello World output. In a console application, we can do this using Console.Writeline:
  - The code implementation for this program is as follows:
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  namespace ConsoleApp1
  {
  class Program
  {
  static void Main(string[] args)
  {
  Console.WriteLine("Hello World");
  }
  }
  }
  - At this stage, we have finished the program and are ready to execute it. Click on Build | Build Solution. Check that there are no compile time errors:
  - At this stage, internally, Visual Studio should have created an .exe application for the project:
  - Open Command Prompt and navigate directly to where the .exe file has been created. Execute the .exe file and check that the desired output of Hello World appears in Command Prompt.
  Summary
  Before we move to the next chapter, let's summarize what we have learned during this chapter. We had a brief recap on the building blocks of C#. We had a walk-through of the .NET Framework architecture and visited the different components in it. We also analyzed what makes C# different from programming languages such as C and C++. We went over the functioning of CLR and how it implements garbage collection in C#. We then wrote our first program, Hello World. By now, you should have a good awareness of what C# is and the features it contains.
  In the next chapter, we will go over some more basic principles of C# programming. We will analyze the different possible access modifiers in C#. Access modifiers make sure that the properties and methods present in a class are only exposed to the relevant modules in an application. We will learn the behavior and implementation of value and reference type data variables in C# programming. We will go over inheritance and interface, and how they are implemented in a C# application. We will discuss the differences between inheritance and interface, and the different scenarios in which we should use one or the other.
  Questions
  - Which of the following statements is correct with regard to C, C++, and C#?
  - C is an object-oriented language.
  - C++ applications are independent of the underlying system.
  - C# applications are independent of the underlying system.
  - C implements all the functionality and features of C++ and C#.
  - An assembly consists of related namespaces and classes that interact with each other to provide a certain functionality.
  - True
  - False
  - For a console project, we can set any function as the starting point of execution for the application.
  - True
  - False
  Answers
  - C is not an object-oriented language. C and C++ are not independent of the underlying platform, unlike C#, which implements the feature using Common language runtime. C is a subset of the functionality and features provided by C# and C++.
  - True. An assembly consists of a number of related namespaces and classes grouped together.
  - False. For a console application, the point of entry is always the main program.