C Sharp Unit-I Notes
C Sharp Unit-I Notes
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
Evaluation of C#
1. SIMPLE
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
4. OBJECT ORIENTED
5. TYPE SAFE
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
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
Java uses static final to declare a class constant while C# uses const.
In java, parameters are always passed by value, c# allows parameters to be passed by reference by Ref
keyword.
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#?
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.
The .NET Framework provides an environment for building, developing and running web services and other
applications. i.e. .NET framework is a management Environment
Note that , Major parts of .NET Framework are actually coded in C#..
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.
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.
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.
We can use the Base classes in the system namespace to perform the following tasks.
We can use them and invoking their methods or by inheriting them through derived classes thus extending their
functionality
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
Microsoft has advanced the .NET strategy in order to provide a number of benefits to developers and users.
Questions :
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
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.
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.
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
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.
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 {
Console.ReadLine();
When the above code is compiled and executed, it produces the following result −
Size of int: 4
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.
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;
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.
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,
@"Tutorials Point";
The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter.
type* identifier;
For example,
char* cptr;
int* iptr;
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.
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;
/* 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
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);
}
}
}