You are on page 1of 20

UNIT-I

1. Introducing c#
What is C# ?
 C# ( Pronounced as c „Sharp‟) is a new computer programming language developed by Microsoft Corporation.
 In January 1999, Dutch software engineer Anders Hejlsberg formed a team to develop C# as a complement to
Microsoft‟s NET framework. Initially, C# was developed as C-Like Object Oriented Language (COOL).
 It is designed for building robust, reliable and durable components to handle real world applications.

Why C# ?
Highlights of c# are as follows

 It is a modern, general purpose programming language


 It is easy to learn
 It is derived form the c and c++ family.
 It is fully OOP language .
 It is Component oriented Language.
 It is intrinsically object oriented and web-enabled.
 It is the only language designed for .NET framework.
 It combines the best features of VB, C++ and JAVA.

Evaluation of C#

Dr. Vilas Hajare


Features / characteristics of c# ( V. Imp)
C# fulfills the need for a language that is easy to write, read and maintain. It also provides the power and
flexibility of c++. The main key features are as follows :

1. SIMPLE

 Unsafe operations such as direct memory manipulation are not allowed.


 In C# there is no usage of "::" or "->" operators.
 Since it's on .NET, it inherits the features of automatic memory management and garbage collection.
 Varying ranges of the primitive types like Integer, Floats etc.
 Integer values of 0 and 1 are no longer accepted as boolean values. Boolean values are pure true or false
values in C# so no more errors of "="operator and "=="operator.
 "==" is used for comparison operation and "=" is used for assignment operation.

2. CONSISTENT

 C# supports an unified type system which eliminates the problem of varying ranges of integer types. All
types are treated as objects and developers can extend the type system simple and easily.

3. MODERN

C# is called as modern Language due to a number of features it supports .


 Automatic garbage collection
 Rich implicitly included model for error handling
 Decimal data type for financial applications
 Modern approach of debugging
 Robust security model

4. OBJECT ORIENTED

C# is truly object oriented . It supports all features of OOP such as :


 Encapsulation
 Inheritance
 Polymorphism
Dr. Vilas Hajare
C# class model is built on top of the Virtual Object System ( VOS) of the .NET Framework

5. TYPE SAFE

 All dynamically allocated objects and arrays are initialized to zero.


 Use of any uninitialized variables produces an error message by the compiler.
 Access to arrays is range-checked and warned if it goes out of bounds.
 In C# we cannot perform unsafe casts like convert double to a boolean.
 C# enforce overflow checking in arithmetic operations.
 Reference parameters that are passed are type-safe
 C# supports automatic garbage collection.

6. VERSIONABLE

 Making new versions of software modules work with the existing applications is known as versioning.
 C # provides support for versioning with the help of new and override keywords.

7. COMPATIBLE

 C # enforces the .NET common Language specifications and therefore allows inter-operations with other
.NET languages.
 C# provides support for transparent access to standard COM and OLE Automation.
 C# also permits interoperation with C-Style API.

8. FLEXIBLE

 Pointers are missing in C# but we may declare certain classes and methods as unsafe‟ and then use
pointers to manipulate them.

9. INTER-OPERABILITY

 C# includes native support for the COM objects and windows based applications.
 C# supports to call out any native API

Applications of c# ( V. V. Imp)
It can be used for various applications that are supported by the .NET platform

 Console applications
 Windows applications
 Providing Web Services
 Developing Windows controls
 Developing ASP.NET projects
 Creating Web Controls
 Developing .NET component Library

Dr. Vilas Hajare


Difference between C++ and C# ( Imp)

Parameter C++ C#
C++ is a low level and platform neutral
Type of language C# is a high-level language.
programming language.
C# 'compiles' down to CLR (Common
Compiling C++ compiles down to machine code Language Runtime), which is interpreted by
JIT in ASP.NET
Memory
In C++, you need to manage memory manually. C# runs memory management automatically
management
Multiple
C++ support the multiple inheritances C# does not support multiple inheritances.
inheritances
C# doesn't have any complex features. It has
Level of difficulty C++ includes more complex features. a simple hierarchy and quite easy to
understand.
Default access
Public in C++. Private in C# .net.
Specifier
C++ is a language that runs on all sorts of
C#, while standardized, is rarely seen
Platform platforms. It is also equally popular on Unix and
outside windows.
Linux systems.
Standalone
C++ can create standalone applications. C# can't make a standalone application.
applications
Object Oriented C++ is not a complete object orient language. C# is a pure object-oriented language.
Bound checking Does not support bound checking of arrays. Supports bound checking of arrays.
Garbage Collection C++ does not support garbage collection. C# supports garbage collection.
Foreach Loop C++ does not support for each loop. C# supports for each loop.
You can use pointer only in the unsafe
Use of pointers You can use pointers anywhere in the program.
mode.
C# programming can be used to create
Used for It allows you to develop only console applications.
Windows, mobile, and console applications.
C# has a lot of overhead and libraries
Size of binaries C++ is much more lightweight.
should be included before it will compile.
C++ programmers generally focus on applications
Type of Projects that work directly with hardware or that need better C# is used for modern app development.
performance than other languages can offer.
C# is highly protected. as it Compiler will
C++ allows you to do almost anything provided the
throw errors and warnings in case you
Compiler warnings syntax is right. Therefore, it is flexible language,
inadvertently write code that can cause
but you may cause serious damage running OS.
damage.
After compiling, C++ code is converted into After compiling, C# code is converted into
Compilation result
machine code. an intermediate language code.
In C++ Switch Statement, the test variable can't be In a C# switch statement, may or may not
Switch statement
a string. be a string.
Class definition not terminated with
Class definition Class definition terminates with semicolon
semicolon

Dr. Vilas Hajare


Difference between C# and JAVA
C# and java both were derived from C++, and therefore they have similar roots, both are widely used for web
programming. We discuss the difference between C# and java these are as follows:

 C# developed by Microsoft, while Java developed by Sun-Microsystems.

 Founder of C# is Anders Hejlsberg. And Founder of JAVA is James Gosling.

 C# has more primitive datatypes as compare to Java.

 Java uses static final to declare a class constant while C# uses const.

 Unlike java, all C# datatypes are object.

 In java, parameters are always passed by value, c# allows parameters to be passed by reference by Ref
keyword.

 C# includes native support for properties, java does not.

 In java, the switch statement can have only integer expression, in C# supports integer and string both.

 C# supports enumerations, type-safe value types which are limited to a defined set of constant variables,
and structures, which are user-defined value types.

 Java doesn't have enumerations, but can specify a class to emulate them.

 Java does not support operator overloading while C# supports operator overloading of multiple operators.

 In Java programming, the concept of jagged array is introduced; these (jagged arrays) are implemented
solely with single-dimensional arrays where arrays can be members of other arrays. In C#, we can also
implement genuine rectangular arrays (which may the replacement of jagged array)

 JAVA does not support delegates, while C# uses delegates, which are type-safe method pointers. These
are used to implement event-handling.

 C# uses CLR (Common Language Runtime) while JAVA uses JVM (Java Virtual Machine).

Questions:
A1. What is c# ?
A2. State any four Applications of C#?

B1. Explain type-safe features of C# .


B2. Explain any three features of C#.
B3. What are the Applications of c#.

C1. Differentiate between C++ and C# .


C2. Differentiate between C# and JAVA.

D1. Explain characteristics/Features of C#.


Dr. Vilas Hajare
2. Understanding . NET and C# Environment

What is .NET ?
 .NET is a Software framework that includes everything required for developing software for web
services. It integrates presentation technologies, component technologies, and data technology on a single
platform so as to enable users to develop Internet applications.
 With .NET , we can use multiple Languages , editors and libraries to build for Web, mobile, desktop,
gaming etc.
 Microsoft produced a coherent systems solution popularly known as Microsoft . NET.

Microsoft .NET strategy


 Microsoft .NET strategy includes the three components :
 Microsoft .NET platform
 Microsoft .NET products and services
 Third party Services

Dr. Vilas Hajare


Origins of .NET Technology

What is the .NET Framework? ( 10 M IMP)

 The .NET Framework provides an environment for building, developing and running web services and other
applications. i.e. .NET framework is a management Environment

Dr. Vilas Hajare


 It is a platform for application developers
 It is a Framework that supports Multiple Language and Cross language integration.
 It has IDE (Integrated Development Environment).
 Framework is a set of utilities or can say building blocks of your application system.
 .NET Framework provides GUI in a GUI manner.
 .NET is a platform independent but with help of Mono Compilation System (MCS). MCS is a middle level
interface.
 .NET Framework provides unique features called interoperability between languages i.e. Common Type
System (CTS) .
 .NET Framework also includes the .NET Common Language Runtime (CLR), which is responsible for
maintaining the execution of all applications developed using the .NET library.

The Common Language Runtime ( CLR) ( V V Imp)


 The Common Language Runtime popularly known as CLR is the heart and soul of the .NET framework
and responsible for loading and running of c# program.
 CLR is runtime environment provided by .NET framework.

Note that , Major parts of .NET Framework are actually coded in C#..

Dr. Vilas Hajare


When the program needs memory, CLR allocates memory for scope and deallocated the memory if the
scope is completed.

Common Type System (CTS)

 The .NET framework provides multiple language support using the feature called as Common Type
Language.
 It supports a variety of types and operations found in most programming languages and therefore calling
one language from another does not require type conversions.
 Example : We can build .NET programs in a number of other languages including C++ and Visual Basic.

Common Language Specification (CLS)

 It declares a set of rules that enables interoperability on the .NET platform. These rules serve as a guide
to third party compiler designers and library builders.
 The CLS is a Subset of CTS and therefore the languages supporting the CLS can use each others class
libraries as if they are their own.
 Application Program Interfaces ( APIs) that are designed follows the rules of CLS can easily be used by
all the .NET languages.

Microsoft Intermediate Language (MSIL)

 MSIL or IL is an instruction set into which all the .NET programs are compiled.
 When we compile a c# program or any program written in CLS – compliant language, the source code is
complied into MSIL.

Managed Code
 The code that satisfies the CLR at run Time in order to execute is referred to as Managed Code.
 Compilers that are compatible to the .NET platform generate managed code.
Dr. Vilas Hajare
 Example : C# compiler generates the managed code. The managed code generated by C# is IL code. The
IL code is then converted to native machine code by the JIT compilers.

Framework base classes


 .NET supplies a library of base classes that we can use to implement applications quickly.
 We can use them and invoking their methods or by inheriting them through derived classes thus
extending their functionality.
 Functionality in the base framework classes resides in the namespace called system.

We can use the Base classes in the system namespace to perform the following tasks.

 Input / Output Operations


 String Handling
 Managing arrays, lists, map etc
 Security
 Windowing
 Drawing
 Connecting to the Internet etc.

User and Program Interfaces


 .NET framework provides the following tools for managing user- and application interfaces:

.Windows Form - (GUI) . Console Applications


.Web Forms . . Web Services
 These tools enables users to develop user friendly desktop-based as well as web based applications using
.NET platform.

We can use them and invoking their methods or by inheriting them through derived classes thus extending their
functionality

Visual Studio .NET

 It supports an Integrated Development Environment(IDE) with a rich set features and productivity tools.
 It is object oriented.
 All developing facilities in internet based application
 Advance error handler and debugger

Dr. Vilas Hajare


. NET Languages

Benefits of .NET Approach (Imp)

Microsoft has advanced the .NET strategy in order to provide a number of benefits to developers and users.

Benefits are as follows :

 Simple and faster system development


 Rich object oriented model
 Enhanced built-in-functionality
 Integration of different Languages into one platform
 Simple and easy to build sophisticated development tools.
 Many ways to communicate with the outside world.
 Fewer bugs
 Potentially better performance.
 Automatic garbage collection.

Questions :

A1. What is .NET ?


A2. What is CLR ?
A3. What is CTS ?
A4. What is manage code?
A5. What are the components of Microsoft .NET strategy ?

B1. What is .NET framework ?


Dr. Vilas Hajare
B2. What are benefits of .NET ?

C1. Explain Microsoft .NET strategy?

C2. Explain Architecture of .NET framework?

C3. Explain Common Language Runtime in brief.

D1. What is CLR ? List and explain components of CLR.

Dr. Vilas Hajare


3. Overview of c#
Kinds of C# program
C# can be used to develop two categories of programs , namely :

1. Executable application program : Programs are written to carry out certain task and require the
method Main in one of the classes. An extension of c source file is .cs .
2. Component Libraries : It does not require a Main( ) declaration because they are not standalone
application programs. They can be written for use by other applications. It is similar to Applets and
application program in JAVA.

Sample C# program
using System ;

Class SampleOne

{ public static void Main( )

{ System.Console.WriteLine ( “This is first sample program in c# ”) ;

Console.ReadKey( );

Structure of C# Program :

 NAMESPACES ( V. V. Imp)
Using system;

Namespaces are the way C# segregates the .NET library classes into reasonable groupings. Here, System is the
keyword for importing namespace (scope) in which the Console class is located. A Class in a namespace can
be accessed using the dot operator . namespace keyword is used to create a namespace in c#.

Using directives that can be used to import the namespace System into the program . Once a namespace is
imported, we can use the elements of the namespace without using namespace as prefix . if we use using
directives then it will automatically search methods in defined namespace and will compile code without any
complaint.

Dr. Vilas Hajare


 Class Declaration
Class sampleone -

Class is a keyword and declares that a new class definition follows. Sampleone is a class name ( identifier)
to be defined. A class is a template for what an object looks like and how it behaves. Everything must be
placed inside a class.

Braces -

It defines the body of the class. class Code block is always enclosed by braces { and }. There should
be no semicolon after closing brace.

 Main () Method
Public static void Main( )

Defines a method named Main. Every C# executable program must include the Main() method in one of the
classes. This is a starting point for executing the program.

Meaning and purpose of keywords used in Main method.

Public - It is a access modifier that tells the c# compiler that the Main method is accessible by anyone.

Static - It declares that the Main method is a global one and can be called without creating an instance of the
class. Compiler stores the address of the method at entry point and uses this information to begin execution
before any objects are created.

Void – This modifier states that the Main method does not return any value .

Body of the main method contains declaration of variables and c# executable statements . Each statement
should be terminated with a ; (semicolon) . code body should be enclosed within the { and } .

Data types
Different data types in c#.net are :

 Value types

 Reference types

 Pointer types

Dr. Vilas Hajare


Value Type (Imp)
Value type variables can be assigned a value directly. They are derived from the class System.ValueType .

The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets,
and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the
value.

The following table lists the available value types in C# 2010 −

Type Represents Range Default


Value

bool Boolean value True or False False

byte 8-bit unsigned integer 0 to 255 0

char 16-bit Unicode character U +0000 to U +ffff '\0'

decimal 128-bit precise decimal values 0.0M


(-7.9 x 1028 to 7.9 x 1028) / 100to 28
with 28-29 significant digits

double 64-bit double-precision floating (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 0.0D


point type

float 32-bit single-precision floating 0.0F


-3.4 x 1038 to + 3.4 x 1038
point type

int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0

long 64-bit signed integer type -9,223,372,036,854,775,808 to 0L


9,223,372,036,854,775,807

sbyte 8-bit signed integer type -128 to 127 0

short 16-bit signed integer type -32,768 to 32,767 0

Dr. Vilas Hajare


uint 32-bit unsigned integer type 0 to 4,294,967,295 0

ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0

ushort 16-bit unsigned integer type 0 to 65,535 0

To get the exact size of a type or a variable on a particular platform, you can use the sizeof method. The
expression sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the
size of int type on any machine −
LivDemo

using System;

class Program {

static void Main(string[] args) {

Console.WriteLine("Size of int: {0}", sizeof(int));

Console.ReadLine();

When the above code is compiled and executed, it produces the following result −

Size of int: 4

Reference Type (Imp)


The reference types do not contain the actual data stored in a variable, but they contain a reference to the
variables. Example class is a reference data type.

In other words, they refer 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. Example of built-in reference types are: object, dynamic and string.

Dr. Vilas Hajare


Object Type
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an
alias for System.Object class. The object types can be assigned values of any other types, value types, reference
types, predefined or user-defined types. However, before assigning values, it needs type conversion.

When a value type is converted to object type, it is called boxing and on the other hand, when an object type is
converted to a value type, it is called unboxing.

object obj;

obj = 100; // this is boxing

Dynamic Type
You can store any type of value in the dynamic data type variable. Type checking for these types of variables
takes place at run-time.

Syntax for declaring a dynamic type is −

dynamic <variable_name> = value;

For example,

dynamic d = 20;

Dynamic types are similar to object types except that type checking for object type variables takes place at
compile time, whereas that for the dynamic type variables takes place at run time.

String Type
The String Type allows you to assign any string values to a variable. The string type is an alias for the
System.String class. It is derived from object type. The value for a string type can be assigned using string
literals in two forms: quoted and @quoted.

For example,

String str = "Tutorials Point";

A @quoted string literal looks as follows −

@"Tutorials Point";

The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter.

Dr. Vilas Hajare


Pointer Type
Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as the
pointers in C or C++.

Syntax for declaring a pointer type is −

type* identifier;

For example,

char* cptr;

int* iptr;

Boxing and Unboxing ( V.V. V. Imp)

Boxing
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of
a value type to the type object or to any interface type implemented by this value type. Boxing a value type
allocates an object instance on the heap and copies the value into the new object.

Consider the following declaration of a value-type variable:


int i = 123;

The following statement implicitly applies the boxing operation on the variable i:
// Boxing copies the value of i into object o.
object o = i;

The result of this statement is creating an object reference o, on the stack, that references a value of the type int,
on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the
two variables, i and o, is illustrated in the following figure.

Boxing Conversion

It is also possible to perform the boxing explicitly as in the following example, but explicit boxing is never
required:
Dr. Vilas Hajare
int i = 123;
object o = (object)i; // explicit boxing

Description

This example converts an integer variable i to an object o by using boxing. Then, the value stored in the
variable i is changed from 123 to 456. The example shows that the original value type and the boxed object use
separate memory locations, and therefore can store different values.

class TestBoxing

{
static void Main()
{
int i = 123;

// Boxing copies the value of i into object o.


object o = i;

// Change the value of i.


i = 456;

// The change in i doesn't affect the value stored in o.


System.Console.WriteLine("The value-type value = {0}", i);
System.Console.WriteLine("The object-type value = {0}", o);
}
}

/* Output:
The value-type value = 456
The object-type value = 123
*/

Unboxing
Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value
type that implements the interface. An unboxing operation consists of:

 Checking the object instance to make sure that it is a boxed value of the given value type.
 Copying the value from the instance into the value-type variable.
int i = 123; // a value type
object o = i; // boxing
int j = (int)o; // unboxing

The following figure demonstrates the result of the previous statements.

Dr. Vilas Hajare


Unboxing Conversion

For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object
that was previously created by boxing an instance of that value type. Attempting to unbox null causes
a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes
an InvalidCastException.
Example :

class TestUnboxing
{
static void Main()
{
int i = 123;
object o = i; // implicit boxing

try
{
int j = (short)o; // attempt to unbox

System.Console.WriteLine("Unboxing OK.");
}
catch (System.InvalidCastException e)
{
System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
}
}
}

This program outputs:

Specified cast is not valid. Error: Incorrect unboxing.

Dr. Vilas Hajare

You might also like