Home Programming Programming in C#: Exam 70-483 (MCSD) Guide

Programming in C#: Exam 70-483 (MCSD) Guide

By Simaranjit Singh Bhalla , SrinivasMadhav Gorthi
books-svg-icon Book
eBook $38.99 $26.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $38.99 $26.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Learning the Basics of C#
About this book
Programming in C# is a certification from Microsoft that measures the ability of developers to use the power of C# in decision making and creating business logic. This book is a certification guide that equips you with the skills that you need to crack this exam and promote your problem-solving acumen with C#. The book has been designed as preparation material for the Microsoft specialization exam in C#. It contains examples spanning the main focus areas of the certification exam, such as debugging and securing applications, and managing an application's code base, among others. This book will be full of scenarios that demand decision-making skills and require a thorough knowledge of C# concepts. You will learn how to develop business logic for your application types in C#. This book is exam-oriented, considering all the patterns for Microsoft certifications and practical solutions to challenges from Microsoft-certified authors. By the time you've finished this book, you will have had sufficient practice solving real-world application development problems with C# and will be able to carry your newly-learned skills to crack the Microsoft certification exam to level up your career.
Publication date:
October 2019
Publisher
Packt
Pages
444
ISBN
9781789536577

 

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: https://www.visualstudio.com/downloads/.

Sample code for this chapter can be found on GitHub at https://github.com/PacktPublishing/Programming-in-C-sharp-Exam-70-483-MCSD-Guide/tree/master/Chapter01.

 

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:

Feature

C#

C

Object-oriented programming

Object-oriented programming is the main essence of any high-level programming language, and C# allows us to utilize the capabilities of OOP using the four main pillars of encapsulation, polymorphism, inheritance, and abstraction. In Chapter 3, Understanding Object-Oriented Programming, we will look at this in detail.

C as a programming language

does not support polymorphism, encapsulation, and inheritance.

It does not provide features such as function overloading, virtual functions, and inheritance.

Exception handling

Exception handling is the process of handling runtime errors that occur during the execution of the application. C# provides us with exception handling features that help us handle these scenarios in a better way. In Chapter 7, Implementing Exception Handling, we will look at this in detail.

C also does not provide any exception handling features.

Type safety

Every variable declared in a program has a type. In a typical type-safe language during the program compilation stage itself, the compiler will validate the values being assigned to variables and raise a compile time error if an incorrect type is assigned to it. C# is a type-safe language. However, in Chapter 8, Creating and Using of Types in C#, we will learn that it also allows you to use pointers using a keyword, UnSafe.

C language implements type safety, albeit with some exceptions. There are certain in-built functions such as printf that do not enforce that only character strings are passed to them.

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++:

Feature

C#

C++

Object-oriented programming

As described previously, C# is a fully object-oriented language.

Similar to C#, C++ is also a fully object-oriented language.

Memory management

C# has got an inbuilt garbage collector that manages the allocation and deallocation of memory. In Chapter 9, Managing the Object Life Cycle, we will understand memory management in C# in detail.

C++ does not have a built-in garbage collector. Due to this, developers are responsible for handling the allocation and deallocation of memory.

Inheritance

C# does not support multiple inheritance. In Chapter 2, Understanding Classes, Structures, and Interfaces, we will learn what it means; however in simple terms, it means that a class can only inherit from one class at a time.

Compared to C# , C++ allows us to implement multi-level inheritance.

Use of pointers

Although C# allows us to use pointers in our code, we need to declare the code with a snippet of UnSafe. We will look into this in detail in Chapter 8, Creating and Using of Types in C#.

C++ allows us to use pointers anywhere without any implicit declaration in the code.

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#.

Microsoft released the first version of .NET 1.0 in 2002. The current version of .NET Framework is 4.8. The code written in this book will be based on this version of .NET Framework 4.7.2.

.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.
For further information on .NET Framework, please refer to the official docs from Microsoft: https://docs.microsoft.com/en-us/dotnet/framework/get-started/overview.

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:

.NET Framework

CLR version

1.0

1.0

1.1

1.1

2.0/3.0/3.5

2.0

4.0/4.5/4.5.1/4.5.2/4.6/4.6.1/4.6.2/4.7/4.7.1/4.7.2/4.8

4

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#:

Version

.NET Framework

Important features in C#

C# 1.0/1.1/1.2

.NET Framework 1.0/1.1

First release of C#

C# 2.0

.NET Framework 2.0

Generics anonymous methods, Nullable types, and Iterators

C# 3.0

.NET Framework 2.0/3.0/3.5/4.0

Query expressions, Lambda expression, and Extension methods

C# 4.0

.NET Framework 2.0/3.0/3.5/4.0

Dynamic binding, Named/optional arguments, and Embedded interop types

C# 5.0

.NET Framework 4.5

Asynchronous members

C# 6.0

.NET Framework 4.6/4.6.2/4.7/4.7.1/4.7.2

Exception filters, String interpolation, nameof operator, and Dictionary initializer

C# 7.0/7.1/7.2/7.3

.NET Framework 4.6/4.6.2/4.7/4.7.1/4.7.2

Out variables, Pattern matching, Reference locals and returns, and Local functions

C# 8

.NET Framework 4.8

Read-only members and Default interface members

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: https://visualstudio.microsoft.com/license-terms/mlt553321/.

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 C# is an object-oriented language, and at the basic level it contains building blocks known as classes. The classes interact with one another, and as a result, provide functionality at runtime. A class consists of two components:

  • Data attributes: Data attributes refer to the different properties defined in the class object.
  • Methods: Methods indicate the different operations that are to be executed in the class object.

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:

  1. 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.

Please note that for a console program, it's not possible to change the default method, which would be the first entry point for the application.
  1. 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.

  1. 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:
Please note that C# is a case-sensitive language. This basically means that if we change the name of the method from Main to main, CLR will not be able to execute this method.

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:

  1. 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");
}
}
}
  1. 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:
  1. At this stage, internally, Visual Studio should have created an .exe application for the project:
  1. 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

  1. 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#.
  2. An assembly consists of related namespaces and classes that interact with each other to provide a certain functionality.
    • True
    • False
  3. For a console project, we can set any function as the starting point of execution for the application.
    • True
    • False
 

Answers

  1. 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++.
  2. True. An assembly consists of a number of related namespaces and classes grouped together.
  3. False. For a console application, the point of entry is always the main program.
About the Authors
  • Simaranjit Singh Bhalla

    Simaranjit Singh Bhalla is working as a Solution Architect with SMS Management and Technology in Sydney, Australia. He has also worked with Microsoft Global Services for a period of 3.5 years. He has worked with Storm Technologies and Accenture Avanade Group earlier. He has around 7 years of experience in C#. He has extensive experience in the development of the Microsoft technology stack. He has done multiple successful engagements in C#, .Net, Azure, Javascript, and CRM, etc. He has completed certifications in .Net 4.0 Framework, Net 4.5 MVC, Programming in C#, Windows Azure and Web Service, etc.

    Browse publications by this author
  • SrinivasMadhav Gorthi

    Madhav is a Multi-skilled senior CRM Consultant having over 9 years experience in C# and Microsoft Dynamics CRM implementations with the expertise to Architect, Design, implement end-to-end solutions & Business Outcomes. He is proficient in planning and delivering applications using Microsoft Technologies which includes integrations and data migrations in-line with best practices & within cost. He is adept in key areas like problem-solving, debugging and troubleshooting and handling service transitions & operations. Madhav has experience in delivering the application using waterfall, Agile and hybrid models as per client expectations. Madhav enjoys leading teams in delivering end-to-end applications with experience in Project Management, Team Management and Stakeholder Management and exposure to Pre-Sales.

    Browse publications by this author
Latest Reviews (2 reviews total)
Will know better when I take the exam
Remove this book form list, once it will be available then you can add in list
Programming in C#: Exam 70-483 (MCSD) Guide
Unlock this book and the full library FREE for 7 days
Start now