Introduction To C#
Introduction To C#
The following reasons make C# a widely used professional language (Features of C#):
1. It is a modern, general-purpose programming language
2. It is object oriented.
3. It is component oriented.
4. It is easy to learn.
5. It is a structured language.
6. It produces efficient programs.
7. It can be compiled on a variety of computer platforms.
8. It is a part of .Net Framework.
Object Orientation
C# is a rich implementation of the object-orientation paradigm, which includes
encapsulation, abstraction, inheritance, and polymorphism. Encapsulation means
creating a boundary around an object, to separate its external (public) behaviour from its
internal (private) implementation details.
The distinctive features of C# from an object-oriented perspective are:
2
Classes and interfaces
In a traditional object-oriented paradigm, the only kind of type is a class. In C#, there are
several other kinds of types, one of which is an interface. An interface is like a class,
except that it only describes members. The implementation for those members comes
from types that implement the interface. Interfaces are particularly useful in scenarios
where multiple inheritance is required (unlike languages such as C++ and Eiffel, C# does
not support multiple inheritance of classes).
Type Safety
C# is primarily a type-safe language, meaning that instances of types can interact only
through protocols they define, thereby ensuring each type’s internal consistency. For
instance, C# prevents you from interacting with a string type as though it were an integer
type.
More specifically, C# supports static typing, meaning that the language enforces type
safety at compile time. This is in addition to type safety being enforced at run‐ time.
Static typing eliminates a large class of errors before a program is even run. It shifts the
burden away from runtime unit tests onto the compiler to verify that all the types in a
program fit together correctly. This makes large programs much easier to manage, more
predictable, and more robust. Furthermore, static typing allows tools such as IntelliSense
in Visual Studio to help you write a program, since it knows for a given variable what type
it is, and hence what methods you can call on that variable.
C# is also called a strongly typed language because its type rules (whether enforced
statically or at runtime) are very strict. For instance, you cannot call a function that’s
3
designed to accept an integer with a floating-point number, unless you first explicitly
convert the floating-point number to an integer. This helps prevent mistakes.
Strong typing also plays a role in enabling C# code to run in a sandbox—an environment
where every aspect of security is controlled by the host. In a sandbox, it is important that
you cannot arbitrarily corrupt the state of an object by bypassing its type rules.
Memory Management
C# relies on the runtime to perform automatic memory management. The Com ‐ mon
Language Runtime has a garbage collector that executes as part of your program,
reclaiming memory for objects that are no longer referenced. This frees programmers
from explicitly deallocating the memory for an object, eliminating the problem of
incorrect pointers encountered in languages such as C++.
C# does not eliminate pointers: it merely makes them unnecessary for most
programming tasks.
Platform Support
Historically, C# was used almost entirely for writing code to run on Windows platforms.
Recently, however, Microsoft and other companies have invested in other platforms,
including Linux, macOS, iOS, and Android.
Xamarin™ allows cross platform C# development for mobile applications, and Portable
Class Libraries are becoming increasingly widespread.
Microsoft’s ASP.NET Core is a cross-platform lightweight web hosting framework that can
run either on the .NET Framework or on .NET Core, an open source cross-platform
runtime.
C# and CLR
C# depends on a runtime equipped with a host of features such as automatic memory
management and exception handling. At the core of the Microsoft .NET Framework is
the Common Language Runtime (CLR), which provides these runtime features. (The .NET
Core and Xamarin frameworks provide similar runtimes.)
C# is one of several managed languages that get compiled into managed code. Man ‐ aged
code is represented in Intermediate Language or IL. The CLR converts the IL into the
native code of the machine, such as X86 or X64, usually just prior to execution. This is
referred to as Just-In-Time (JIT) compilation. Ahead-of-time compilation is also available
to improve start up time with large assemblies or resource constrained devices (and to
satisfy iOS app store rules when developing with Xamarin).
5
Common Language Runtime(CLR):
CLR is the basic and Virtual Machine component of the .NET Framework. It is the run-time
environment in the .NET Framework that runs the codes and helps in making the
development process easier by providing the various services such as remoting, thread
management, type-safety, memory management, robustness etc. Basically, it is
responsible for managing the execution of .NET programs regardless of any .NET
programming language. It also helps in the management of code, as code that targets the
runtime is known as the Managed Code and code doesn’t target to runtime is known as
Unmanaged code.
The core libraries are sometimes collectively called the Base Class Library (BCL). The
entire framework is called the Framework Class Library (FCL).
6
class library includes types that support a variety of specialized development scenarios.
For example, you can use the .NET Framework to develop the following types of
applications and services:
1. Console applications
2. Windows GUI applications (Windows Forms).
3. Windows Presentation Foundation (WPF) applications.
4. ASP.NET applications.
5. Windows services.
6. Service-oriented applications using Windows Communication Foundation (WCF).
7. Workflow-enabled applications using Windows Workflow Foundation (WF).
7
Table 5-1 shows the history of compatibility between each version of C#, the CLR, and the
.NET Framework.
Other Frameworks
The Microsoft .NET Framework is the most expansive and mature framework, but runs
only on Microsoft Windows (desktop/server). Over the years, other frame‐ works have
emerged to support other platforms. There are currently three major players besides
the .NET Framework, all of which are currently owned by Microsoft:
Xamarin
For writing mobile apps that target iOS, Android, and Windows Mobile. The Xamarin
company was purchased by Microsoft in 2016.
9
Table 1-1 compares the current platform support for each of the major frameworks
Net Standard has solved all this in a different way, it provided an API specification which
all platforms should implement to remain .Net Standard complaint. This has unified the
base class libraries of different .Net platforms and has paved way to share libraries and
also brought the BCL evolution centralized as seen below.
10
.NET Standard 2.0 is a new version that significantly increases the number of APIs
compared to the previous version (1.6.1). In fact, the API surface has more than doubled
with .NET Standard 2.0.
The 1.x standards lack thousands of APIs that are present in 2.0, including much of what
we describe in this book. This can make targeting a 1.x standard significantly more
challenging, especially if you need to integrate existing code or libraries.
If you need to support older frameworks but don’t need cross platform compatibility, a
better option is to target an older version of a specific framework. In the case of
Windows, a good choice is .NET Framework 4.5 because it’s widely deployed (pre-
installed on all machines running Windows 8 and later), and it contains most of what’s
in .NET Frame‐ work 4.7.
11
You can also think of .NET Standard as a lowest common denominator. In the case of .NET
Standard 2.0, the four frameworks that implement it have a similar Base Class Library, so
the lowest common denominator is big and useful. However, if you also want
compatibility with .NET Core 1.0 (with its significantly cut-down BCL), the lowest common
denominator—.NET Standard 1.x—becomes much smaller and less useful.
System Types
The most fundamental types live directly in the System namespace. These include C#’s
built-in types, the Exception base class, the Enum, Array, and Delegate base classes, and
Nullable, Type, DateTime, TimeSpan, and Guid. The System namespace also includes
types for performing mathematical functions (Math), generating random numbers
(Random), and converting between various types (Convert and Bit Converter).
Text Processing
The System.Text namespace contains the StringBuilder class (the editable or mutable
cousin of string), and the types for working with text encodings, such as UTF-8 (Encoding
and its subtypes).
The System.Text.RegularExpressions namespace contains types that perform advanced
pattern-based search-and-replace operations.
Collections
The .NET Framework offers a variety of classes for managing collections of items. These
include both list- and dictionary-based structures, and work in conjunction with a set of
standard interfaces that unify their common characteristics. All collection types are
defined in the following namespaces:
Queries
Language Integrated Query (LINQ) was added in Framework 3.5. LINQ allows you to
perform type-safe queries over local and remote collections (e.g., SQL Server tables). A
big advantage of LINQ is that it presents a consistent querying API across a variety of
domains. The essential types reside in the following namespaces, and are part of .NET
Standard 2.0:
12
XML
XML is used widely within the .NET Framework, and so is supported extensively. The XML
name‐ spaces are:
Diagnostics
Diagnostics refers to .NET’s logging and assertion facilities and describe how to interact
with other processes, write to the Windows event log, and use performance counters for
monitoring. The types for this are defined in and under System.Diagnostics. Windows-
specific features are not part of .NET Standard, and are avail‐ able only in the .NET
Framework.
Networking
You can directly access standard network protocols such as HTTP, FTP, TCP/IP, and SMTP
via the types in System.Net.
The latter two namespaces are unavailable to Windows Store applications if you’re
targeting Windows 8/8.1 (WinRT), but are available to Windows 10 Store apps (UWP) as
part of the .NET Standard 2.0 contract. For WinRT apps, use third-party libraries for
sending mail, and the WinRT types in Windows.Networking.Sockets for working with
sockets.
Serialization
The Framework provides several systems for saving and restoring objects to a binary or
text representation. Such systems are required for distributed application technologies,
13
such as WCF, Web Services, and Remoting, and also to save and restore objects to a file.
The types for serialization reside in the following namespaces:
Dynamic Programming
Dynamic Language Runtime, which has been a part of the CLR since Framework 4.0. The
types for dynamic programming are in System.Dynamic.
Security
Code access, role, and identity security, and the transparency model introduced in CLR
4.0. Cryptography can be done in the Framework, covering encryption, hashing, and data
protection. The types for this are defined in:
System.Security
System.Security.Permissions
System.Security.Policy
System.Security.Cryptography
Advanced Threading
C#’s asynchronous functions make concurrent programming significantly easier because
they lessen the need for lower-level techniques. However, there are still times when you
need signaling constructs, thread-local storage, reader/writer locks, and so on. Threading
types are in the System.Threading namespace.
14
Applied Technologies
Descriptions of .NET Implementations
User-Interface APIs
User-interface–based applications can be divided into two categories: thin client, which
amounts to a website, and rich client, which is a program the end user must download
and install on a computer or mobile device.
For thin client applications, .NET provides ASP.NET and ASP.NET Core.For rich-client
applications that target Windows 7/8/10 desktop, .NET provides the WPF and Windows
Forms APIs. For rich-client apps that target iOS, Android, and Windows Phone, there’s
Xamarin, and for writing rich-client store apps for Win‐ dows 10 desktop and devices.
Finally, there’s a hybrid technology called Silverlight, which has been largely abandoned
since the rise of HTML5.
ASP.NET
Applications written using ASP.NET host under Windows IIS and can be accessed from any
web browser. Here are the advantages of ASP.NET over rich-client technologies:
There is zero deployment at the client end.
Clients can run a non-Windows platform.
Updates are easily deployed.
In writing your web pages, you can choose between the traditional Web Forms and the
newer MVC (Model-View-Controller) API. Both build on the ASP.NET infra ‐ structure.
Web Forms has been part of the Framework since its inception; MVC was written much
later in response to the success of Ruby on Rails and MonoRail. It provides, in general, a
better programming abstraction than Web Forms; it also allows more control over the
generated HTML.
15
ASP.NET Core
A relatively recent addition, ASP.NET Core is similar to ASP.NET, but runs on both .NET
Framework and .NET Core (allowing for cross-platform deployment). ASP.NET Core
features a lighter-weight modular architecture, with the ability to self-host in a custom
process, and an open source license. Unlike its predecessors, ASP.NET Core is not
dependent on System.Web and the historical baggage of Web Forms. It’s particularly
suitable for micro-services and deployment inside containers.
Windows Forms
Windows Forms is a rich-client API that’s as old as the .NET Framework. Com ‐ pared to
WPF, Windows Forms is a relatively simple technology that provides most of the features
you need in writing a typical Windows application. It also has significant relevancy in
maintaining legacy applications. It has a number of drawbacks, though, compared to
WPF:
Controls are positioned and sized in pixels, making it easy to write applications
that break on clients whose DPI settings differ from the developer’s (although this
has improved somewhat in Framework 4.7).
The API for drawing nonstandard controls is GDI+, which, although reasonably
flexible, is slow in rendering large areas (and without double buffering, may
flicker).
Controls lack true transparency.
Most controls are non-compositional. For instance, you can’t put an image control
inside a tab control header. Customizing list views and combo boxes is time-
consuming and painful.
Dynamic layout is difficult to get right reliably
Xamarin
Xamarin, now owned by Microsoft, lets you write mobile apps in C# that target iOS and
Android, as well as Windows Phone. Being cross-platform, this runs not on the .NET
Framework, but its own framework (a derivation of the open source Mono framework).
16
UWP (Universal Windows Platform)
UWP is for writing apps that target Windows 10 desktop and devices, distributed via the
Windows Store. Its rich-client API is designed for writing touch-first user interfaces, and
was inspired by WPF and uses XAML for layout. The namespaces are Windows.UI and
Windows.UI.Xaml.
Silverlight
Silverlight is also distinct from the .NET Framework, and lets you write a graphical UI that
runs in a web browser, much like Macromedia’s Flash. With the rise of HTML5, Microsoft
has abandoned Silverlight.
Backend Technologies
ADO.NET
ADO.NET is the managed data access API. Although the name is derived from the 1990s-
era ADO (ActiveX Data Objects), the technology is completely different. ADO.NET contains
two major low-level components:
Provider layer
The provider model defines common classes and interfaces for low-level access to
database providers. These interfaces comprise connections, commands, adapters, and
readers (forward-only, read-only cursors over a database). The Framework ships with
native support for Microsoft SQL Server, and numerous third-party drivers are available
for other databases.
DataSet model
A DataSet is a structured cache of data. It resembles a primitive in-memory database,
which defines SQL constructs such as tables, rows, columns, relationships, constraints,
and views. By programming against a cache of data, you can reduce the number of trips
to the server, increasing server scalability and the responsiveness of a rich-client user
interface. DataSets are serializable and are designed to be sent across the wire between
client and server applications.
Sitting above the provider layer are three APIs that offer the ability to query databases via
LINQ:
Entity Framework (.NET Framework only)
Entity Framework Core (.NET Framework and .NET Core)
LINQ to SQL (.NET Framework only)
LINQ to SQL is simpler than Entity Framework, and has historically produced better SQL
(although Entity Framework has benefited from numerous updates).
Entity Framework is more flexible in that you can create elaborate mappings between
the database and the classes that you query (Entity Data Model), and offers a model that
allows third-party support for databases other than SQL Server.
17
Entity Framework Core (EF Core) is a rewrite of Entity Framework with a simpler design
inspired by LINQ to SQL. It abandons the complex Entity Data Model and runs on both
.NET Framework and .NET Core.
WCF further decouples the client and server through service contracts and data
contracts. Conceptually, the client sends an (XML or binary) message to an end ‐ point on
a remote service, rather than directly invoking a remote method. One of the benefits of
this decoupling is that clients have no dependency on the .NET plat‐ form or on any
proprietary communication protocols.
For .NET-to-.NET communication, however, WCF offers richer serialization and better
tooling than with REST APIs. It’s also potentially faster as it’s not tied to HTTP and can use
binary serialization.
The types for communicating with WCF are in, and below, the System.Service Model
namespace.
18
Web API
Web API runs over ASP.NET/ASP.NET Core and is architecturally similar to Microsoft’s
MVC API, except that it’s designed to expose services and data instead of web pages. Its
advantage over WCF is in allowing you to follow popular REST over HTTP conventions,
offering easy interoperability with the widest range of platforms.
REST implementations are internally simpler than the SOAP and WS- protocols that WCF
relies on for interoperability. REST APIs are also architecturally more elegant for loosely-
coupled systems, building on de-facto standards and making excellent use of what HTTP
already provides.
Its growing popularity has made it the first choice of many experienced and fresher and
now one can think of having a great career start in this field outside India too. .Net is now
part of many international markets like USA, UAE, South Africa, UK and other developing
countries and is heading forward with each passing day. With its every new version .Net
technologies is evolving at a fast pace and creating amazing job opportunities for the
developers.
The availability of RAD in.Net, which means the Rapid Application Development is the
reason behind its success. The plus point of learning this technology is that you can
develop as many applications as you want for different platforms and environments. You
can even use it for building XML web applications and web services that can excellently
run on the Internet. .Net is best suited for developing window based applications, web
server programs and applications, which are both PC and mobile compatible. It’s easy to
transfer feature is what makes it the popular choice.
The biggest advantage of learning .net is that one can get a job in various profiles like
he/she can be absorbed as a software developer also or a.Net technician too. Today,
there are an array of institutes and firms that offer certified and short term course in
.Net, which
19
is a great move from career point of view. Whether you are a diploma holder or an
Engineer or an MCA, learning .Net will surely set your career and will offer it a right pace
and track. There are ample of career options in this particular field. An interested
candidate can go for MCTS(VB.net), MCTS(ASP.net) and MCPD, which are some of the
international certifications. You can even choose from Cisco certifications like CCNA,
CCNP, CCIE, which will give a new direction to your career.
With so many job prospects in this technology, choosing it will be an ideal choice for your
career. This clearly illustrates the future scope of .Net, which is sure to offer you great
future ahead in almost all the spheres, ranging from Desktop applications to mobile
applications.
20
Procedure-Oriented vs. Object-Oriented Programming
Object-Oriented Programming (OOP) is a high-level programming language where a
program is divided into small chunks called objects using the object-oriented model,
hence the name. This paradigm is based on objects and classes.
Object – An object is basically a self-contained entity that accumulates both data
and procedures to manipulate the data. Objects are merely instances of classes.
Class – A class, in simple terms, is a blueprint of an object which defines all the
common properties of one or more objects that are associated with it. A class can
be used to define multiple objects within a program.
The OOP paradigm mainly eyes on the data rather than the algorithm to create modules
by dividing a program into data and functions that are bundled within the objects. The
modules cannot be modified when a new object is added restricting any non-member
function access to the data. Methods are the only way to assess the data.
Objects can communicate with each other through same member functions. This process
is known as message passing. This anonymity among the objects is what makes the
program secure. A programmer can create a new object from the already existing objects
by taking most of its features thus making the program easy to implement and modify.
21
In POP, Most function uses Global data for In OOP, data cannot move easily from function
sharing that can be accessed freely from to function, it can be kept public or private so
function to function in the system. we can control the access of data.
POP does not have any proper way for hiding OOP provides Data Hiding so provides more
data so it is less secure. security.
In POP, Overloading is not possible. In OOP, overloading is possible in the form of
Function Overloading and Operator
Overloading.
Example of POP are : C, VB, FORTRAN, Pascal. Example of OOP are : C++, JAVA, VB.NET,
C#.NET.
22