You are on page 1of 37

Module 1:

Getting started with .NET Framework 4.0 and C#

What is .NET framework


 .NET Framework is a software development framework for building and
running applications on Windows.
 .NET Framework is part of the .NET platform, a collection of technologies for
building apps for Linux, macOS, Windows, iOS, Android, and more.
 .Net framework consists of developer tools, programming languages, and
libraries to build desktop and web applications.
 In simple terms, a .Net framework is a virtual machine (VM) for assembling
and performing programs written in multiple languages like C#, VB.Net, etc.
 It also includes an IDE called Visual Studio for writing programs
 It is also used to build websites, web services, and games.

Benefits of .NET Framework:


1. Object-Oriented Programming (OOP)
One of the best things about .NET is that it is based on object-oriented
programming (OOP). It is easy to divide the tasks in independent modules and
then later combine them to produce the solution to complex problems.

2. Portability
Applications built on the .Net framework can be made to work on any Windows
platform. And now in recent times, Microsoft is also envisioning to make
Microsoft products work on other platforms, such as iOS and Linux.

3. Easy to Deploy and Maintain


The deployment of applications and their maintenance could not be done easier
with the help of the .NET family of development tools.

4. Open source:
The .NET framework is opensource which inturn is free to use and explore as
well as wide support in development and enhancement of product and
technologies.
5. Large community
The .NET has managed to build a huge community ever since it was launched,
but it was not until it was made open-source by Microsoft that it really exploded.

6. Security
The .NET Framework has a good security mechanism. The inbuilt security
mechanism helps in both validation and verification of applications. Every
application can explicitly define their security mechanism. Each security
mechanism is used to grant the user access to the code or to the running program.

7. Simplified deployment
The .Net framework also have tools, which can be used to package applications
built on the .Net framework. These packages can then be distributed to client
machines. The packages would then automatically install the application.

8. Simplicity
Executing usual jobs using the .NET platform is very simple and straightforward.
Besides, the submission of forms is very easier, and also there are site design,
deployment, and client consent.

9. Monitoring
Ultimately, the net platform also stands for its monitoring automation. It will
punctually notice any issues such as immense loops, memory leaks, etc. Not only
this, but it will also terminate these activities automatically and restart itself.
.NET Framework architecture:

(Refer the other diagram)

The architecture of .Net framework is based on the following key components;


Common Language Runtime
The “Common Language Infrastructure” or CLI is a platform in .Net
architecture on which the .Net programs are executed.

The CLI has the following key features:


Exception Handling – Exceptions are errors which occur when the application
is executed.
Examples:
If an application tries to open a file on the local machine, but the file is not
present.

Garbage Collection
Garbage collection is the process of removing unwanted resources when they
are no longer required.
Examples
A File handle which is no longer required. If the application has finished all
operations on a file, then the file handle may no longer be required.

Components of CLR:
A developer can develop an application in a variety of .Net programming
languages.
Language – The first level is the programming language itself; the most
common ones are VB.Net and C#.
Compiler – There is a compiler which will be separate for each programming
language. e.g., C#, you will have its own compiler. This compiler will generate
intermediate code.
Common Language Interpreter – CLI is the interpreter that takes the compiler
generated code in intermediary language. Programs written in all the languages
will be generated in common intermediary language. Which will then be
converted to byte code and executed.

Class Library
The .NET Framework includes a set of standard class libraries. A class library is
a collection of methods and functions that can be used for the core purpose.

For example, there is a class library with methods to handle all file-level
operations eg., Methods intended for performing reading and writing operations
on the file.

3. Languages
The types of applications that can be built in the .Net framework is classified
broadly into the following categories.

WinForms – This is used for developing Forms-based applications, which


would run on an end user machine.
Example: Notepad
ASP.Net - This is used for developing web-based applications, which are made
to run on any browser such as Internet Explorer, Chrome or Firefox.
The applications are processed server side and displayed to the user.

ADO.Net - This technology is used to develop applications to interact with


Databases such as Oracle or Microsoft SQL Server.

Features of .NET Framework:


There are several features of the .Net framework that offer smooth functioning
of operations. These are as follows;
Memory management
The .Net framework includes all the capability to look after those resources that
are not useful by a running program. It would then release or free those
resources finally. This is carried on through a program known as the “Garbage
Collector”. The waste collector runs at regular intervals and keeps on checking
all the files, codes, etc.

Common Type System


In .NET framework there is a common type system to include working with
data types across different languages is easy as it is in uniformity in standards
that define the type system in all .NET based languages.

Extensive Class Library


In place of writing large size code to manage usual low-level coding operations,
programmers use a readily available library type for this. And they also use their
members from the .NET Framework Class Library (FCL).

Interoperability
The platform allows a lot of backend support. In case if the user had an
application created on an older version like 2.0 of this framework. And if he
tried to run the same application on a system that includes the higher version of
the platform, such as 3.5. Besides, the application would still continue to work.
This is because Microsoft ensures with every release that the older framework
versions also support well with the newer version.
Portability
Apps build on the .Net platform can be made to perform on any Windows
platform. And now in present times, Microsoft is also imagining to make its
products work on other platforms. Like iOS and Linux OS.

Security
The .NET framework includes a good security system. The inbuilt security
system helps in both validation and confirmation of apps. Every app can define
its security system in a clear and complete manner. Moreover, each security
system is useful to allow the user access to the code or to the running program.

Simplified deployment
The .Net framework includes some tools that are useful to package applications
built on the .Net platform. Later, these packages can be spread to client systems.
Further, the packages would automatically install the application.

Version compatibility
With rare anomalies, apps that are built by using a specific version of.NET
framework run without change in a later version. This is a great thing here.

.NET Remoting
.Net framework Remoting now supports Ipv6 addresses and the exchange of
common types. .NET facilitates authentication, encryption and other security
parameters. This can enhance the execution of network load-balancing by
remote clusters.

Managed Extensibility Framework


The Managed Extensibility Framework or MEF is the latest library within the
.NET Framework version 4. This helps users to develop very extensible and
designer apps. Moreover, it allows users to define points where an application
extension takes place to uncover services to offer to other extensible apps.
Further, they are useful to build parts for utilization by extensible apps.

Parallel Computing
The .Net Framework ver.4 presents a new program model for writing
multithreaded and asynchronous code. This model greatly clarifies the job of an
application and library developers. The latest model allows developers to write
systematic, and highly scalable parallel code in a natural idiom. It doesn’t need
to work directly with threads.

.NET for Windows Store Apps


The Windows Store Apps built for particular form factors and leverage the
power of the Windows OS. A part of the .Net framework 4.5 versions is
available for developing Windows Store apps. This is useful for Windows by
using C# or VB.
.NET Framework Architecture: (Refer this for architecture)
The architecture of the .Net framework is a kind of programming model for the
Net platform under which it offers a managed performance environment,
development, and deployment in the simplest way.

Furthermore, the.Net framework architecture is based on some key components


that include;
 CLR- Common Language Runtime
 CLS - Common Language Specification
 BCL - Base Class Library
 CTS - Common Type Specification
 FCL - .Net Framework Class Library
 CLI - Common Language Infrastructure

Common language runtime (CLR)


Common Language Runtime (CLR) is an interoperable runtime environment
from the .Net framework which provides an environment to run all .Net
programs. It helps in converting the source code to native code; It is a two-step
process where the source code is first converted to a Microsoft Intermediate
Language (MSIL) and then CLR uses JIT compilers to convert MSIL code to
native code. There are over 15 language compilers that convert the source code
to MSIL code.
CLR takes care of exception handling, memory, and thread management. CLR
contains a Garbage Collector (GC) which takes care of memory management by
cleaning up out-of-scope objects from the memory.

Common Language Specification (CLS)


CLS is a subset of CLR. CLS comes in handy when codes of different
programming languages based on the .Net framework are referred to in the
same solution. There are many programming languages that have .Net as the
background. Different programming languages with different syntaxes will
generate a MSIL. Which will follow a uniform standard. And then it is
converted to byte code. CLS is very important to integrate the programs written
in different languages.

Base Class Library (BCL)

The base class library encapsulates a large number of common functions which
can be used by the developers. They are the foundational types and act as the
base for all the .NET class libraries. App-specific libraries will be built on top of
BCL.

They are developed with general implementations with a high-performance


policy such as low-latency, high throughput, low-memory, and low-CPU usage.

Features such as ADO.Net, XML handling, Threading, Security, Diagnosis, etc.,


are part of the base class library.

Framework class library (FCL)


Framework Class Library is a collection of classes, interfaces, namespace, data,
and value types that are used for .Net applications. It is a superset of the base
class library. It consists of in-built classes that support base and user-defined
data types, input/output and streaming operations, web-client, server, and
Windows based GUI applications creation and underlying communication
systems.
The functionality of FCL can be broadly classified into three categories.
 Utility Features,
 Wrapper Around OS functionality, and
 Frameworks
Utility features include different collection classes. For example list, stack,
queue, dictionary, etc. It also includes regular expression (regex) classes.

Wrapper around OS functionality includes classes that act as a wrapper to


communicate with OS components such as file system, network features, and
console application operations.

Frameworks include the technology used to develop ASP.NET web application,


Windows Presentation Foundation (WPF), etc.

Common Language Infrastructure(CLI)


The CLI or Common Language Infrastructure provides a language-independent
platform for app development and its performance. It also includes the function
for exception handling, waste collection, security, etc.
the CLI is the last layer in the net framework.
This would be useful to run a .net program built in any coding language. So the
afterward compiler will send the coding to the CLI layer to run the .Net
application.
Metadata and Assemblies:
Metadata in .Net is binary information which describes the characteristics of a
resource.
This information includes Description of the Assembly, Data Types and
members with their declarations and implementations, references to other types
and members, Security permissions etc.
A module's metadata contains everything that needed to interact with another
module.

During the compile time Metadata created with Microsoft Intermediate


Language (MSIL) and stored in a file called a Manifest.
Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped
in a Portable Executable (PE) file.
During the runtime of a program Just in Time (JIT) compiler of the Common
Language Runtime (CLR) uses the Metadata and converts Microsoft
Intermediate Language (MSIL) into native code.
When code is executed, the runtime loads metadata into memory and references
it to discover information about your code's classes, members, inheritance, and
so on. Moreover, Metadata eliminating the need for Interface Definition
Language (IDL) files, header files, or any external method of component
reference.
Microsoft .NET Assemblies:

 Microsoft .Net Assembly is a logical unit of code, that contains code which
the Common Language Runtime (CLR) executes.
 It is the smallest unit of deployment of a .net application and it can be a .dll
or an exe .
 Assembly is really a collection of types and resource information that are
built to work together and form a logical unit of functionality.
 It include both executable application files that you can run directly from
Windows without the need for any other programs (.exe files), and libraries
(.dll files) for use by other applications.

 Assemblies are the building blocks of .NET Framework applications.

 During the compile time Metadata is created with Microsoft Intermediate


Language (MSIL) and stored in a file called Assembly Manifest .

 Both Metadata and Microsoft Intermediate Language (MSIL) together


wrapped in a Portable Executable (PE) file. Assembly Manifest contains
information about itself.

 This information is called Assembly Manifest, it contains information about


the members, types, references and all the other data that the runtime needs
for execution.
.NET frame work class library

NET Framework Class Library is the collection of classes, namespaces, interfaces


and value types that are used for .NET applications.

It contains thousands of classes that supports the following functions.


 Base and user-defined data types.
 Support for exceptions handling.
 input/output and stream operations.
 Communications with the underlying system.
 Access to data.
 Ability to create Windows-based GUI applications.
 Ability to create web-client and server applications.
 Support for creating web services.

WindowsForms
Windows Forms is a Graphical User Interface(GUI) class library which is
bundled in .Net Framework.
Its main purpose is to provide an easier interface to develop the applications for
desktop, tablet, PCs. It is also termed as the WinForms.
The applications which are developed by using Windows Forms or WinForms
are known as the Windows Forms Applications that runs on the desktop
computer.
WinForms can be used only to develop the Windows Forms Applications not
web applications.
WinForms applications can contain the different type of controls like labels, list
boxes, tooltip etc.
ASP.NET
It is a web framework designed and developed by Microsoft. It is used to
develop websites, web applications and web services.
It provides fantastic integration of HTML, CSS and JavaScript. It was first
released in January 2002.
It is built on the Common Language Runtime (CLR) and allows programmers to
write code using any supported .NET language.

ASP.NET AJAX
Asynchronous JavaScript and XML (AJAX) is a development technique used to
create interactive web applications or rich internet applications. AJAX uses a
number of existing technologies together, including: XHTML, CSS, JavaScript,
Document Object Model, XML, XSLT, and the XMLHttpRequest object.
With AJAX, web applications can retrieve data from the server asynchronously,
in the background, without reloading the entire browser page. The use of AJAX
has led to an increase in interactive animation on web pages.

AJAX is about updating parts of a web page, without reloading the whole page.
AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes. This means that it is possible
to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the
content should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and
Facebook tabs.
AJAX applications are browser- and platform-independent!
Advantages
 Reduces the traffic travels between the client and the server.
 No cross browser pain.
 Better interactivity and responsiveness.
 With AJAX, several multi purpose applications and features can be handled
using a single web page(SPA).
 API's are good because those work with HTTP method and JavaScript.

Disadvantages
 Search engines like Google would not be able to index an AJAX application.
 It is totally built-in JavaScript code. If any user disables JS in the browser, it
won't work.
 The server information cannot be accessed within AJAX.
 Security is less in AJAX applications as all the files are downloaded at client
side.
 The data of all requests is URL-encoded, which increases the size of the
request.

ADO.NET:
ADO.NET is a module of .Net Framework which is used to establish connection
between application and data sources.
Data sources can be such as SQL Server and XML. ADO.NET consists of
classes that can be used to connect, retrieve, insert and delete data.
ADO.NET provides a bridge between the front-end controls and the back-end
database.
The ADO.NET objects encapsulate all the data access operations and the
controls interact with these objects to display data, thus hiding the details of
movement of data.
ADO.NET is a set of classes (a framework) to interact with data sources such as
databases and XML files. ADO is the acronym for ActiveX Data Objects. It
allows us to connect to underlying data or databases. It has classes and methods
to retrieve and manipulate data.
The following are a few of the .NET applications that use ADO.NET to connect
to a database, execute commands and retrieve data from the database.
 ASP.NET Web Applications
 Console Applications
 Windows Applications.

Windows Workflow Foundation (WWF or WF) is a framework for creating


and managing workflows within .NET applications. It treats each step of a
process as an activity, working with a .NET library of activities and adding
custom activities for other kinds of functionality. A Visual Studio tool called
Workflow Designer helps visualize these workflows.

Windows Presentation Foundation (WPF) is a development framework used


to create a desktop application. It is a part of the .NET framework. The WPF has
a resolution-independent and vector-based rendering engine which is helpful to
deal with modern graphics hardware. The latest version of WPF is 4.6. In this
framework, UI of the application is designed in XAML language and
Application logic is Written in C# programming language.
Features of WPF are as following:
 Extensible Application Markup Language (XAML)
 Controls
 Data Binding
 Layout
 2D and 3D graphics
 Animation
 Styles
 Templates
 Documents
 Media
 Text
 Typography

Windows Communication Foundation:


WCF stands for Windows Communication Foundation. It is a framework for
building, configuring, and deploying network-distributed services. Earlier
known as Indigo, it enables hosting services in any type of operating system
process. This tutorial explains the fundamentals of WCF and is conveniently
divided into various sections. Every section of this tutorial has adequate number
of examples to explain different concepts of WCF.

Windows CardSpace
Windows CardSpace was developed by Microsoft as a software program for the
Identity Metasystem. CardSpace was used to create digital identities for users,
storing some personal information about them that could be requested and
accessed by websites or other software applications. Users also had the ability
to create personal cards as well, utilizing up to 14 fields to store information.
When users' information, or identity, was requested, the CardSpace UI would
appear, looking somewhat like a business card or Outlook Contact with
information about the user. The user can select what card to make available to a
website or application, which results in the website or application requesting a
digitally signed XML token. This token would then contain the information
being requested about the user.
Microsoft originally included Windows CardSpace with the .NET Framework
3.0, which was designed to run on Windows XP, Windows Vista and Windows
Server 2003. It is installed by default on Windows Vista and Windows 7, and
can be downloaded for Windows XP and Windows Server 2003 for free.
Microsoft has since discontinued Windows CardSpace, opting to put time and
resources into developing a replacement call U-Prove.

LINQ:
LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET
to retrieve data from different sources and formats. It is integrated in C# or VB,
thereby eliminating the mismatch between programming languages and
databases, as well as providing a single querying interface for different types of
data sources.
For example, SQL is a Structured Query Language used to save and retrieve
data from a database. In the same way, LINQ is a structured query syntax built
in C# and VB.NET to retrieve data from different types of data sources such as
collections, ADO.Net DataSet, XML Docs, web service and MS SQL Server
and other databases.
LINQ queries return results as objects. It enables you to uses object-oriented
approach on the result set and not to worry about transforming different formats
of results into objects.
Introduction to C#
C# (C-Sharp) is a programming language developed by Microsoft that runs on
the .NET Framework.

C# is used to develop web apps, desktop apps, mobile apps, games and much
more.

Basic Hello World C# Program

using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}

The first statement in any C# program is

using System;
The using keyword is used for including the namespaces in the program. A
program can include multiple using statements

Comments:
Single-line comments are indicated by the '//' symbol. For example,
//This is a comment
The multiline comments in C# programs start with /* and terminates with the
characters */
/* This is a
Multiline comment */
C# Keywords:
Keywords are predefined sets of reserved words that have special meaning in a
program. The meaning of keywords cannot be changed, neither can they be
directly used as identifiers in a program.
C# has a total of 79 keywords. All these keywords are in lowercase.
Here is a complete list of all C# keywords.

Contextual Keywords
Besides regular keywords, C# has 25 contextual keywords. Contextual
keywords have specific meaning in a limited program context and can be used
as identifiers outside that context. They are not reserved words in C#.

C# Identifiers:
Identifiers are the name given to entities such as variables, methods, classes, etc.
They are tokens in a program which uniquely identify an element. For example,
Rules for Naming an Identifier
 An identifier can not be a C# keyword.
 An identifier must begin with a letter, an underscore or @ symbol. The
remaining part of identifier can contain letters, digits and underscore symbol.
 Whitespaces are not allowed. Neither it can have symbols other than letter,
digits and underscore.
 Identifiers are case-sensitive. So, vcetMCA, vcetmca and Vcetmac
represents 3 different identifiers.

Note:
PascalCase for public member variables (string MyName = "James")
camelCase for local variables (string myName = "James")
_leadingUnderscore for private member variables (string _myName = "James")
Primitive Data types in C#

Variables and Constants in C#:


A variable is a value that might change during the execution of a program.
A variable must be declared as a particular type such as an integer, a character or
a string. C# is what is known as a strongly typed language in that once a variable
has been declared as a particular type it cannot subsequently be changed to a
different type.

int x, y=20;
x=10;
x=y;
Constants are similar to variables but once a value is assigned it can’t be changed
during the execution of the program. Constants differ in one significant way in
that once a value has been assigned to a constant it cannot subsequently be
changed.
const int x=10; //Valid
const int x;
x=10 //Invalid

In C#, these data types are categorized based on how they store their value in the
memory. C# includes the following categories of data types:
 Value type
 Reference type
 Pointer type

Value Type:
A data type is a value type if it holds a data value within its own memory space.
It means the variables of these data types directly contain values.
For example, consider integer variable int i = 100;
The system stores 100 in the memory space allocated for the variable i.

Value type data types include:


Bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct,
uint, ulong, ushort

Reference Type
Unlike value types, a reference type doesn't store its value directly. Instead, it
stores the address where the value is being stored. In other words, a reference
type contains a pointer to another memory location that holds the data.
For example, consider the following string variable:
string s = "Hello World!!";
As you can see in the above image, the system selects a random location in
memory (0x803200) for the variable s. The value of a variable s is 0x600000,
which is the memory address of the actual data value. Thus, reference type
stores the address of the location where the actual value is stored instead of the
value itself.
Reference type data types include:
 String
 Arrays (even if their elements are value types)
 Class
 Delegate

3. Pointer Type:
Pointer type or pointer variables refers to those variables that holds the address
of another variables.
int x=100;
int *ptr = & x;.
Here ptr holds the address of x.
*ptr is used to represent the value stored in the address held by ptr variable.
&- address of x
&x represents assignment of address of x to pointer variable ptr.

Type conversion in C#:


Type conversion is converting one type of data to another type. It is also known
as Type Casting. In C#, type casting has two forms.

Implicit type conversion –


In implicit type conversion, the C# compiler automatically converts one type to
another.
Char->int->float->double
Generally, smaller types like int (having less memory size) are automatically
converted to larger types like double (having larger memory size). These
conversions are performed by C# in a type-safe manner.
int x=50;
double y=x; //Implicit conversion
In the above example the integer type value stored in variable x is implicitly
converted to variable y which is of type double.

Explicit type conversion - These conversions are done explicitly by users using
the pre-defined functions. Explicit conversions require a cast operator.
Generally, larger types like double (having large memory size) are converted to
smaller types like int (having small memory size).
There is a possible chance of data loss in this type of conversion.
// Explicit casting
double y=100.123
int x = (int) y;
Now the double type is converted to int type explicitly.
Here, (int) is a cast expression that explicitly converts the double type to int
type.

C# explicit type conversion using Parse()


In C#, we can also use the Parse() method to perform type conversion.
Generally, while performing type conversion between non-compatible types like
int and string, we use Parse().
//Example
string n = "100";
int a = int.Parse(n);
C# Type Conversion using Convert Class
In C#, we can use the Convert class to perform type conversion. The Convert
class provides various methods to convert one type to another.

int num = 100;


string str = Convert.ToString(num);

value 100 of type int stored in variable num is converted to string data type and
stored in string variable str.
Example 2: Convert.ToDouble(num) - converts num to the Double type.

Boxing and Unboxing in C#


namespace ExampleBU
{
class Program
{
static void Main(string[] args)
{
int x = 10;
object y = x; //Boxing
int z = (int)y; //Unboxing
}
}
}
Explanation:
Boxing means you basically set a value type to a reference type and unboxing
means you basically set a reference type to a value type.
C# has two kinds of data types, value types and reference types. Value type stores
the value itself, whereas the reference type stores the address of the value where
it is stored. Some predefined data types such as int, float, double, decimal, bool,
char, etc. are value types and object, string, and array are reference types.
While working with these data types, you often need to convert value types to
reference types or vice-versa. Because, both have different characteristics and
.NET stores them differently in the memory, it must do some work internally to
convert them from one type to another. These conversion processes are called
boxing and unboxing.
Boxing is the process of converting a value type to the object type or any
interface type implemented by this value type. Boxing is implicit.
Unboxing is the reverse of boxing. It is the process of converting a reference
type to value type. Unboxing extract the value from the reference type and
assign it to a value type. Unboxing is explicit.
It means we have to cast explicitly.

The casting of a boxed value is not permitted. The following will throw an
exception.
First perform unboxing and then casting.
Namespaces in C#:
Namespaces play an important role in managing related classes in C#.

The .NET Framework uses namespaces to organize its built-in classes.

For example, there are some built-in namespaces in .NET such as System,
System.Linq, System.Web, etc. Each namespace contains related classes.

A namespace is a container for classes and namespaces. The namespace also


gives unique names to its classes thereby you can have the same class name in
different namespaces.
In C#, a namespace can be defined using the namespace keyword.
Syntax:
namespace namespace_name
{
}

Example:
namespace VCET
{

class UG
{
//Member data and member functions
}
class PG
{
//Member data and member functions
}

Classes under the same namespace can be referred to as namespace.classname


syntax. For example, the Student class can be accessed as VCET.PG.
To use classes under a namespace without the fully qualified name, import the
namespace with the using keyword at the top of C# class file.
A namespace can contain other namespaces. Inner namespaces can be separated
using (.).
namespace VCET.VC
{
Class academics
{}
}
Note: It is not possible to use any access specifiers like private, public etc with a
namespace declarations. The namespaces in C# implicitly have public access
and this is not modifiable.

Nested Namespaces example:


using System;
namespace Outer{
namespace Inner{
class MyClass{
public MyClass(){
Console.WriteLine("My Class");
}}}}
class MyClient{
public static void Main(){
Outer.Inner.MyClass mc = new Outer.Inner.MyClass();
}}

System namespace:
Contains fundamental classes and base classes that define commonly-used value
and reference data types, events and event handlers, interfaces, attributes, and
processing exceptions.
The using System; line means that you are using the System library in your
project. Which gives you some useful classes like Console or functions/methods
like WriteLine.
C# arrays:
 Array in C# is a group of similar types of elements that have contiguous
memory location. In C#.
 Array is an object of base type System.Array.
 In C#, array index starts from 0.
 We can store only fixed set of elements in C# array.

Advantages of C# Array
 Code Optimization (less code)
 Random Access
 Easy to traverse data
 Easy to manipulate data
 Easy to sort data etc.
Disadvantages of C# Array
 Fixed size

C# Array Types

There are 3 types of arrays in C# programming:


1. Single Dimensional Array
2. Multidimensional Array
3. Jagged Array

C# Single Dimensional Array


To create single dimensional array, you need to use square brackets [] after the
type.

int[] arr = new int[5];//creating array

[] has to be placed after the keyword(int) and not after the identifier(arr).
Which if misplaced throws a compile time error.

Intializing the above declared array can be done in following ways.

1. First Declaration and then Initialization.


int[] arr = new int[5];//
arr[0] = 10;//initializing array position 0
arr[1] = 10;//initializing array position 1

2. Declaration and initialization simultaneously in following ways.


int[] arr = new int[5]{ 10, 20, 30, 40, 50 };
or
int[] arr = new int[]{ 10, 20, 30, 40, 50 }; //Omitting the size of array.
or
int[] arr = { 10, 20, 30, 40, 50 }; //Omitting the new operator.

3. The array can be initialized using for loop.

/* initializing elements of array n to 10 */


for ( i = 0; i < 10; i++ ) {
n[ i ] = 10;
}

Values stored in loops can be traversed using foreach loop:


//traversing array example.
foreach (int i in arr)
{
Console.WriteLine(i);
}

Multidimensional array:
To create a 2D array, add each array within its own set of curly braces, and
insert a comma (,) inside the square brackets:
int[,] numbers = { {1, 4, 2}, {3, 6, 8}};

Note:
The single comma [,] specifies that the array is two-dimensional. A three-
dimensional array would have two commas: int[,,].

numbers is now an array with two arrays as its elements. The first array element
contains three elements: 1, 4 and 2, while the second array element contains 3, 6
and 8. To visualize it, think of the array as a table with rows and columns:

To access an element of a two-dimensional array, you must specify two indexes:


one for the array, and one for the element inside that array.
Console.WriteLine(numbers[0, 2]);//output 2

Change value to a 2D array:


numbers[0, 0] = 5; // Change value to 5

Loop through numbers:


foreach (int i in numbers)
{
Console.WriteLine(i);
}
Alternatively we can use 2 for loops.
C# Jagged Arrays:
In C#, jagged array is also known as "array of arrays" because its elements are
arrays. The element size of jagged array can be different.

Declaration of Jagged array:


int[][] arr = new int[2][];

Let's see an example to initialize jagged array. The size of elements can be
different.
arr[0] = new int[4];

arr[0] = new int[4] { 11, 21, 56, 78 };

Intialization of Jagged array at the time of Declaration:


int[][] arr = new int[3][]{
new int[] { 11, 21, 56, 78 },
new int[] { 2, 5, 6, 7, 98, 5 },
new int[] { 2, 5 }
};

Let's see an example,

// declare jagged array


int[ ][ ] jaggedArray = new int[2][ ];
Here,

 int - data type of the array


 [][] - represents jagged array
 jaggedArray - name of the jagged array
 [2][] - represents the number of elements (arrays) inside the jagged array

Since we know each element of a jagged array is also an array, we can set the
size of the individual array.

For example,
// set size of the first array as 3
jaggedArray[0] = new int[3];

// set size of second array as 2


jaggedArray[1] = new int[2];

1. Using the index number

Once we declare a jagged array, we can use the index number to initialize it. For
example,
// initialize the first array
jaggedArray[0][0] = 1;
jaggedArray[0][1] = 3;
jaggedArray[0][2] = 5;

// initialize the second array


jaggedArray[1][0] = 2;
jaggedArray[1][1] = 4;
Here,

index at the first square bracket represents the index of the jagged array element
index at the second square bracket represents the index of the element inside
each element of the jagged array.

2. Initialize without setting size of array elements

// declaring string jagged array


int[ ][ ] jaggedArray = new int[2] [ ];

// initialize each array


jaggedArray[0] = new int[] {1, 3, 5};
jaggedArray[1] = new int[] {2, 4};

3. Initialize while declaring Jagged Array

int[ ][ ] jaggedArray = {
new int[ ] {10, 20, 30},
new int[ ] {11, 22},
new int[ ] {88, 99}
};
Accessing elements of a jagged array
We can access the elements of the jagged array using the index number. For
example,

// access first element of second array


jaggedArray[1][0];

// access second element of the second array


jaggedArray[1][1];

// access second element of the first array


jaggedArray[0][1];

Iterating through Jagged array:


// outer for loop
for (int i = 0; i < jaggedArray.Length; i++) {
Console.Write("Element "+ i +": ");
// inner for loop
for (int j = 0; j < jaggedArray[i].Length; j++) {
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}

You might also like