0% found this document useful (0 votes)
136 views55 pages

C# Unit 1

This document provides an overview of the .NET Framework and C# programming language, detailing their components, features, and functionalities. It explains the architecture of the .NET Framework, including the Common Language Runtime (CLR) and Framework Class Library (FCL), as well as the types of applications that can be developed using C#. Additionally, it compares C# with Java, outlines C# data types and variables, and describes the compilation process and operators in C#.

Uploaded by

Karthik Vijay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
136 views55 pages

C# Unit 1

This document provides an overview of the .NET Framework and C# programming language, detailing their components, features, and functionalities. It explains the architecture of the .NET Framework, including the Common Language Runtime (CLR) and Framework Class Library (FCL), as well as the types of applications that can be developed using C#. Additionally, it compares C# with Java, outlines C# data types and variables, and describes the compilation process and operators in C#.

Uploaded by

Karthik Vijay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

C# and .

NET Framework
UNIT-I
INTRODUCTION

Overview of .NET Framework – Basic Elements of C# - Common Language


Runtime – Working with .NET Framework and SDK – Understanding the C#
compiler – Operators – C# pre-processing Directives – Enumerated types – Strings,
Arrays, Reference and Value Types.
1.1 Overview of the .NET Framework
• The .NET Framework is the infrastructure for the new Microsoft .NET
Platform.
• The .NET Framework is a common environment for building,
deploying, and running Web Services and Web Applications.
• The .NET Framework contains common class libraries - like
ADO.NET, ASP.NET and Windows Forms - to provide advanced standard
services that can be integrated into a variety of computer systems.
• The .NET Framework is language neutral. Currently it supports C++,
C#, Visual Basic, JScript (The Microsoft version of JavaScript) and COBOL.
Third-party languages - like Eiffel, Perl, Python, Smalltalk, and others - will
also be available for building future .NET Framework applications.
• NET Framework supports more than 60 programming languages in
which 11 programming languages are designed and developed by
Microsoft.
• The remaining Non-Microsoft Languages are supported by .NET
Framework but not designed and developed by Microsoft.

There are three significant phases of the development of .NET


technology.
• OLE Technology
• COM Technology
• .NET Technology
• OLE Technology: OLE (Object Linking and Embedding) is one of
the technologies of Microsoft’s component document. Basically, its
main purpose is to link elements from different applications within
each other.

• COM Technology: The technology of the Microsoft Windows family


of the operating system, Microsoft COM (Common Object Model)
enables various software components to communicate. COM is mostly
used by developers for various purposes like creating reusable
software components, linking components together to build
applications, and also taking advantage of Windows services. The
objects of COM can be created with a wide range of programming
languages.
• .NET Technology: .NET technology of collection or set of
technologies to develop and windows and web applications.

• The technology of .Net is developed by Microsoft and was launched in


Feb. 2002, by basic definition, Microsoft’s new Internet Strategy.

• It was originally called NGWS (Next Generation Web Services).

• It is considered to be as one of the powerful, popular and very much


useful Internet Technology available today.
11 Programming Languages which are
designed and developed by Microsoft are:
• C#.NET
• VB.NET
• C++.NET
• J#.NET
• F#.NET
• JSCRIPT.NET
• WINDOWS POWERSHELL
• IRON RUBY
• IRON PYTHON
• C OMEGA
• ASML (Abstract State Machine Language)
• Microsoft provides a comprehensive Integrated Development Environment (IDE) for the development
and testing of software with .NET.
MAIN COMPONENTS OF .NET FRAMEWORK
• 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 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 that doesn’t target to runtime is known as Unmanaged code.
• Programs developed with .NET needs a virtual machine to run on a host. This virtual
machine is called Common Language Runtime (CLR).

• Framework Class Library (FCL): It is the collection of reusable, object-oriented class


libraries and methods, etc that can be integrated with CLR. Also called the Assemblies.
• It is just like the header files in C/C++ and packages in java. Installing the .NET framework
basically is the installation of CLR and FCL into the system. Below is the overview of
the .NET Framework.
BASIC ARCHITECTURE AND COMPONENT STACK OF .NET FRAMEWORK

• The .NET Framework is composed of four main components:


• Common Language Runtime (CLR)
• Framework Class Library (FCL),
• Core Languages (WinForms, ASP.NET, and ADO.NET), and
• Other Modules (WCF, WPF, WF, Card Space, LINQ, Entity
Framework, Parallel LINQ, Task Parallel Library, etc.)
1. CLR (Common Language Runtime): It is a run-time environment
which executes the code written in any .NET programming
language. .Net framework provides the support for many languages like
C#, F#, C++, Cobra, Jscript.Net, VB.Net, Oxygene etc

2. FCL (Framework Class Library): A large number of class libraries


are present in this framework which is known as FCL.
It is a standard library that is a collection of thousands of classes
and used to build an application. The BCL (Base Class Library) is the
core of the FCL and provides basic functionalities.

3. Types of Applications: Mainly the applications which are built


in .Net framework is divided into the following three categories:
• WinForms: Form – Based applications are considered under this category. In simple terms, we can say client
based applications which read and writes the file system comes under this category.

• ASP .NET: Web-Based applications come under this category. ASP.Net is a framework for web and it provides
the awesome integration of HTML, CSS and JavaScript which makes it useful to develop the web applications,
websites and web services. Web services were added in .Net Framework 2.0 and considered as a part of ASP.NET
web applications.

• ADO .NET: It includes the application which are developed to communicate with the database like MS SQL
Server, Oracle etc. comes. It mainly consists of classes that can be used to connect, retrieve, insert and delete
data.
4. WPF (Windows Presentation Foundation): Windows Presentation Foundation (WPF) is a graphical
subsystem given by Microsoft which uses DirectX and is used in Windows-based applications for rendering UI
(User Interface). WPF was initially released as part of .NET Framework 3.0 in 2006 and previously known as
“Avalon”.
5. WCF (Windows Communication Foundation): It is a framework for building connected and service-oriented
applications used to transmit the data as asynchronous from one service endpoint to another service point. It was
previously known as the Indigo.
6. WF (Windows Workflow Foundation): It is a technology given by Microsoft which provides a platform for
building workflows within .Net applications.
7. Card Space: It is a Microsoft .NET Framework software client which is designed to let users provide their digital identity to
online services in a secure, simple and trusted way.

8. LINQ (Language Integrated Query): It is introduced in .Net framework version 3.5. Basically, it is a query language used to
make the query for data sources with VB or C# programming languages.

9. Entity Framework: It is open–source ORM (Object Relational Mapping) based framework which comes into .Net Framework
version 3.5. It enables the .Net developer to work with database using .Net objects. Before entity framework, .Net developers have
performed a lot of things related database.

10. Parallel LINQ (Language Integrated Query): It comes in .Net Framework version 4.0 and also termed as PLINQ. It provides
a concurrent query execution engine for LINQ. It executes the LINQ in parallel such that it tries to use as much processing power
system on which it is executing.

11. TPL (Task Parallel Library): It is a set of public types and APIs. It allows the developers to be more productive by simplifying
the process of adding concurrency and parallelism to .Net applications.

12. .NET API For Store/UWP Apps: In 2012, Microsoft added some APIs for creating UWP (Universal Windows Platform) apps
for Windows using C# or VB.

13. Task-Based Asynchronous Model: It is model used to describe the asynchronous operations and tasks in .Net Framework.
1.2 BASIC ELEMENTS OF C#
C# is a programming language of .Net Framework. C# is a programming language
of .Net Framework. By the help of C# programming language, we can develop different
types of secured and robust applications:

• Window applications
• Web applications
• Distributed applications
• Web service applications
• Database applications etc.

• Windows From Application - This is GUI based, runs in a window of some sort
• Console Application - This application runs in the command prompt
Java C#
1) Java is a high level, robust, secured and object- C# is an object-oriented programming language
oriented programming language developed by developed by Microsoft that runs on .Net Framework.
Oracle.
2) Java programming language is designed to be C# programming language is designed to be run on
run on a Java platform, by the help of Java the Common Language Runtime (CLR).
Runtime Environment (JRE).
3) Java type safety is safe. C# type safety is unsafe.
4) In java, built-in data types that are passed by In C#, built-in data types that are passed by value are
value are called primitive types. called simple types.
5) Arrays in Java are direct specialization of Arrays in C# are specialization of System.
Object.
6) Java does not support conditional compilation. C# supports conditional compilation using
preprocessor directives.
7) Java doesn't support goto statement. C# supports goto statement.
8) Java doesn't support structures and unions. C# supports structures and unions.
9) Java supports checked exception and C# supports unchecked exception.
unchecked exception.
C# Features
C# is object oriented programming language. It provides a lot of features that are given below.
• Simple
• Modern programming language
• Object oriented
• Type safe
• Interoperability
• Scalable and Updateable
• Component oriented
• Structured programming language
• Rich Library
• Fast speed
C# Example: Hello World
In C# programming language, a simple "hello world" program can be written by multiple
ways. Let's see the top 4 ways to create a simple C# example:
1. System Example
2. Using System
3. Using public modifier
4. Using namespace
1. C# Example: Simple Example
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Hello World!");
}
}
Output:
Hello World!
2. C# Example: Using System
If we write using System before the class, it means we don't need to specify System namespace
for accessing any class of this namespace. Here, we are using Console class without specifying
System.Console.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
Output:
Hello World!
3. C# Example: Using public modifier
We can also specify public modifier before class and Main() method. Now, it can be
accessed from outside the class also.
using System;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
} }
Output:
Hello World!
4. C# Example: Using namespace
We can create classes inside the namespace. It is used to group related classes. It is used to categorize
classes so that it can be easy to maintain.
using System;
namespace ConsoleApplication1
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}}
Output:
Hello World!
C# Variable
A variable is a name of memory location. It is used to store data. Its
value can be changed and it can be reused many times. It is a way to represent
memory location through symbol so that it can be easily identified. The basic
variable type available in C# can be categorized as:
Variable Type Example
Decimal types decimal
Boolean types True or false value, as
assigned
Integral types int, char, byte, short, long
Floating point types float and double
Nullable types Nullable data types

Syntax to declare a variable:


type variable_list;
C# Data Types:
A data type specifies the type of data that a variable can store
such as integer, floating, character etc.

There are 3 types of data types in C# language.


Types Data Types

Value Data Type short, int, char, float,


double etc
Reference Data Type String, Class, Object
and Interface
Pointer Data Type Pointers
1.3 Common Language Runtime
• NET CLR is a runtime environment that manages and executes the
code written in any .NET programming language. CLR is the virtual
machine component of the .NET framework.
• That language's compiler compiles the source code of applications
developed using .NET compliant languages into CLR's intermediate
language called MSIL, i.e., Microsoft intermediate language code.
This code is platform-independent. It is comparable to byte code in
java.
The main components of CLR are:
1. Common type system (CTS)
2. Common language Specification (CLS)
3. Garbage Collector
4. Just in Time Compiler
5. Metadata
6. Assemblies
Common Type System (CTS):
CTS provides guidelines for declaring, using, and managing data
types at runtime. It offers cross-language communication.
For example, VB.NET has an integer data type, and C# has an int
data type for managing integers.
After compilation, Int32 is used by both data types. So, CTS
provides the data types using managed code.
A common type system helps in writing language-independent
code.
It provides two categories of Types.
1. Value Type: A value type stores the data in memory allocated on the
stack or inline in a structure. This category of Type holds the data
directory. If one variable's value is copied to another, both the
variables store data independently. It can be of inbuilt-in types, user-
defined, or enumerations types.
Built-in types are primitive data types like numeric, Boolean, char, and
date. Users in the source code create user-defined types. An enumeration
refers to a set of enumerated values represented by labels but stored as a
numeric type.
2. Reference Type

A Reference type stores a reference to the value of a memory address and is


allocated on the heap.
• Heap memory is used for dynamic memory allocation. Reference Type does
not hold actual data directly but holds the address of data.
• Whenever a reference type object is made, it copies the address and not
actual data. Therefore two variables will refer to the same data.
• If data of one Reference Type object is changed, the same is reflected for the
other object.
• Reference types can be self-describing types, pointer types, or interference
types.
• The self-describing types may be string, array, and class types that store
metadata about themselves.
.NET CLR Functions
Following are the functions of the CLR.
• It converts the program into native code.
• Handles Exceptions
• Provides type-safety
• Memory management
• Provides security
• Improved performance
• Language independent
• Platform independent
• Garbage collection
1.4 WORKING WITH .NET FRAMEWORK AND SDK

SDK Framework
SDK stands for Software Development
Framework (Software Framework) is
Kit. It includes tools and utilities required
basically a platform which is used for
for the development of the applications. It
developing software applications. It
Definition often includes files to interface to a
provides the necessary foundation on
particular programming language,
which the programs can be developed for a
sophisticated hardware to interact with an
specific platform.
embedded system, debugging tools, etc.
Application
Programming Generally, it includes one or two API Technically, a framework includes an API
Interface
Key Feature Tools for developing applications Platform for developing applications
Android Application Framework for
Example Windows 7 SDK
Android
1.5 UNDERSTANDING THE C# COMPILER
Source code Compilation process

Compilation and run time process


1.6 C# OPERATORS
An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise etc. There are following types of
operators to perform different types of operations in C# language.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Unary Operators
• Ternary Operators
• Misc Operators
using System;
namespace Arithmetic
{
class GFG
{
static void Main(string[] args)
{
int result;
int x = 10, y = 5;
// Addition
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
// Subtraction
result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);
// Multiplication
result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result);
// Division
result = (x / y);
Console.WriteLine("Division Operator: " + result);
// Modulo
result = (x % y);
Console.WriteLine("Modulo Operator: " + result);
Precedence of Operators in C#
Category (By Precedence) Operator(s) Associativity

Unary + - ! ~ ++ -- (type)* & sizeof Right to Left


Additive +- Left to Right
Multiplicative %/* Left to Right
Relational < > <= >= Left to Right
Shift << >> Left to Right
Equality == != Right to Left
Logical AND & Left to Right
Logical OR | Left to Right
Logical XOR ^ Left to Right
Conditional OR || Left to Right
Conditional AND && Left to Right
Null Coalescing ?? Left to Right
Ternary ?: Right to Left
Assignment = *= /= %= += - = <<= >>= &= ^= |= => Right to Left
1.7 C# PRE-PROCESSING DIRECTIVES
Preprocessor Directive Description
#define It defines a sequence of characters, called symbol.

#undef It allows you to undefine a symbol.


#if It allows testing a symbol or symbols to see if they evaluate to true.
#else It allows to create a compound conditional directive, along with #if.
#elif It allows creating a compound conditional directive.
#endif Specifies the end of a conditional directive.
#line It lets you modify the compiler's line number and (optionally) the file name output
for errors and warnings.
#error It allows generating an error from a specific location in your code.
#warning It allows generating a level one warning from a specific location in your code.
#region It lets you specify a block of code that you can expand or collapse when using the
outlining feature of the Visual Studio Code Editor.
#endregion It marks the end of a #region block.
The #define Preprocessor
The #define preprocessor directive creates symbolic constants.
#define lets you define a symbol such that, by using the symbol as the expression passed to the #if directive, the
expression evaluates to true. Its syntax is as follows −#define symbol

The following program illustrates this


#define PI
using System;
namespace PreprocessorDAppl {
class Program {
static void Main(string[] args) {
#if (PI)
Console.WriteLine("PI is defined");
#else
Console.WriteLine("PI is not defined");
#endif
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
PI is defined
1.8 ENUMERATED TYPES
An enumerated type, or enum as it’s called in C#, offers a convenient way to create a structured set
of symbols to represent constant values. An enumeration is a set of named integer constants. An enumerated
type is declared using the enum keyword.
C# enumerations are value data type. In other words, enumeration contains its own values and
cannot inherit or cannot pass inheritance.
The general syntax for declaring an enumeration is:
enum <enum_name>
{
enumeration list
};
Where,
• The enum_name specifies the enumeration type name.
• The enumeration list is a comma-separated list of identifiers.
Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that
precedes it. By default, the value of the first enumeration symbol is 0.
For example: enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
1.9 STRINGS
Strings are used for storing text. A string variable contains a collection of characters surrounded by
double quotes. C# uses the + operator for both addition and concatenation.
Example:
Create a variable of type string and assign it a value:
using System;
namespace MyApplication{
class Program
{
static void Main(string[] args)
{
string greeting = "Hello";
Console.WriteLine(greeting);
} }
}
String Length
A string in C# is actually an object, which contain properties and methods that can perform certain
operations on strings. For example, the length of a string can be found with the Length property:
Example:
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.WriteLine("The length of the txt string is: " + txt.Length);
Output:
The length of the txt string is: 26
There are many string methods available, for example ToUpper() and ToLower(), which returns a copy of
the string converted to uppercase or lowercase.
Example:
string txt = "Hello World";
Console.WriteLine(txt.ToUpper()); // Outputs "HELLO WORLD"
Console.WriteLine(txt.ToLower()); // Outputs "hello world"
Output:
HELLO WORLD
hello world
String Concatenation
The + operator can be used between strings to combine them. This is called concatenation.
Example:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string firstName = "John ";
string lastName = "Doe";
string name = firstName + lastName; (or) string name = string.Concat(firstName, lastName);
Console.WriteLine(name);
} }
}
Output:
John Doe
String Interpolation
Another option of string concatenation, is string interpolation, which substitutes values of variables into
placeholders in a string. Note that you do not have to worry about spaces, like with concatenation.

Example:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string firstName = "John";
string lastName = "Doe";
string name = $"My full name is: {firstName} {lastName}";
Console.WriteLine(name);
}
}}
1.10 ARRAYS
C# Arrays
Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value. To declare an
array, define the variable type with square brackets:
Syntax:
string[] cars;
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myNum = {10, 20, 30, 40};
Access the Elements of an Array
To access an array element by referring to the index number. This statement accesses the value of the
first element in cars. Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Example:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]);
} }
}
Output:
Volvo
Sort Arrays foreach (string i in cars)
{
There are many array methods available, for example Console.WriteLine(i);
Sort(), which sorts an array alphabetically or in an }
ascending order.
using System; // Sort an int
int[] myNumbers = {5, 1, 8, 9};
namespace MyApplication Array.Sort(myNumbers);
{ foreach (int i in myNumbers)
{
class Program Console.WriteLine(i);
{ } } }
}
static void Main(string[] args) Output:
{ BMW
// Sort a string Ford
Mazda
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; Volvo
Array.Sort(cars); 1
5
8
9
Other Ways to Create an Array

In C#, there are different ways to create an array.


// Create an array of four elements, and add values later
string[] cars = new string[4];
// Create an array of four elements and add values right away
string[] cars = new string[4] {"Volvo", "BMW", "Ford", "Mazda"};
// Create an array of four elements without specifying the size
string[] cars = new string[] {"Volvo", "BMW", "Ford", "Mazda"};
// Create an array of four elements, omitting the new keyword, and without specifying the size
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
1.11 REFERENCE AND VALUE TYPES
1. Value type
• Variable name contains the actual value
• int, double and other primitive types
• Structure, Enumeration, etc.
Value type variables can be assigned a value directly. The value types are derived from the class
System.ValueType. The value types directly contain data. When you declare an int type, the system allocates
memory to store the value. Value Type variables are stored in the stack.
Examples are int, char, and float, which stores numbers, alphabets, and floating-point numbers, respectively.
2. Reference Type
• Variable name contains the reference or
• pointer to the actual value in memory
• Array, derived from class Array
• Class, Interface, Delegate, String, etc.
It refers to a memory location. Using multiple variables, the reference types can refer to a memory
location. If the data in the memory location is changed by one of the variables, the other variable
automatically reflects this change in value. Reference Type variables are stored in the heap.
Example of built-in reference types are – object, dynamic, string.
1. 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. Example, consider integer variable int i = 100;
All the value types derive from System.ValueType, which in-turn, derives from System.Object. The system
stores 100 in the memory space allocated for the variable i. The following image illustrates how 100 is stored at some
hypothetical location in the memory (0x239110) for 'i':

Memory Allocation of Value Type Variable


2. 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!!";
The following image shows how the system allocates the memory for the above string variable.

Memory Allocation of Reference Type Variable

You might also like