Thursday 11 July 2013

INTRODUCTION TO C SHARP


INTRODUCTION TO C SHARP




C# is intended to be the premier language for writing NGWS(Next Generation Windows Services) application in the enterprise computing space. It is derived from C and C++.



C# is a mordern programming language. It simplifies and modernizes C++ in the areas of classes, namespaces, method overloading and exception handling. Much of the complexity of C++ is removed from C# to make it easier to use and less error prone.



C# eliminates certain features of C++. New features added to C# are strict type safety, versioning, garbage collection, etc.



Features Of C#


1.         Simple

Feature of pointers missing in C# - unsafe operations such as direct memory manipulation not allowed – unified type system, ie every type can be viewed as an object – through “boxing” and unboxing”, simple types can be accessed as objects only when requested.

2.         Mordern

Decimal type for monetary calculations – data types can be specifically created for any type of application – memory management through garbage collection – robust error handling mechanisms through exception handling.

3.         Object_Oriented

Supports all OO concepts – no global functions, variables and constants – everything must be encapsulated in a class – methods of class are non-virtual ie, cannot be overridden – supports protected, public and internal access modifiers – multiple inheritance not allowed – implemented using interfaces – uses delegates instead of function pointers.

4.         Type-Safe

Uninitialized variables cannot be used – performs bounds checking on array elements – reference parameters are type safe.


5.         Versionable

Using this, binary compatibility of applications with the existing client application can be retained.

6.         Compatible

Allows access to different APIs – supports OLE automation – Native APIs can be accessed using Platform Invocation Services(Pinvoke) which provides for interoperating with C APIs.

7.         Flexible

By default, C# runs in safe mode – pointers can be used using unsafe code.



Compiling And Running C#


VS.Net allows us to invoke it graphically from the IDE. If we have .NET Framework SDK, we can compile and run the program from the command line itself.

 


Data Types


1. Value Types

A variable of a certain value type holds a value of that type. When assigning a value to a value type, the value is actually copied. Value types directly contain their data.

2. Reference Types

The actual value remains at the same memory location, but now two objects point to it. Reference types are accessed indirectly using reference variables that point to that object.



Value Types

Simple Types


Struct Types

Enumeration Types



Reference Types

Classes


Interfaces

Delegates

Arrays



Predefined Types


Name
Description

object

Base type of all other types
sbyte
8 bit singed integer
short
16 bit singed integer
int
32 bit singed integer
long
64 bit singed integer
byte
8 bit unsinged integer
ushort
16 bit unsinged integer
uint
32 bit unsinged integer
ulong
64 bit unsinged integer
float
single precision floating point
double
double precision floating point
bool
boolean value
char
Unicode character
decimal
precise decimal with 28 digits



object and string are predefined reference types. All other classes are based on Object.



Console Input

Std input stream is used to get character input. Read() returns a single character as an int or -1 if no more characters are available. ReadLine() returns a string containing next line of input or null if no more lines are available.







Escape Sequances And Strings

An escape sequence is anything that starts with a \. A string is anything within double quotes. A literal string starts with a @ sign and all escape sequences are ignored by the C# compiler and displayed literally.



Operators

Category
Operators
Arithmetic
+ - / * %
Logical
&&   ||   !
String concatenation
+
Increment/Decrement(Unary)
++   --
Comparision
== != < > <= >=
Assignment
= += -= /= %=
Conditional
? :
Member access
.
Cast
()
Object creation
new
Type information
is  sizeof typeof
Indexing
[ ]



Boxing And Unboxing

Value types can be converted to objects by boxing them and back again by unboxing them. Boxing a value refers to implicitly converting any value type to the type of object. When a value type is boxed, an object instance is allocated and the value of the value type is copied into the object. In contrast to boxing, unboxing does an explicit operation. We have to inform the compiler which value type is to be extracted from the object.

***BoxUnbox.cs***





Programming Constructs



if and goto statement

The goto statements jumps to a label specified elsewhere in the code.



switch statement



Loops

for

while

do…while



foreach loop

It is used to iterate over the elements in arrays and collections.

foreach(<type> <var> in <collection>)

{

//statements

}



break and continue statements





Arrays

Arrays in C# are accessed through a reference variable.

***ArrayDemo1.cs***



Multidimensional arrays

In rectangular array, every row is of the same length whereas in a jagged array, the rows may be of different length.

***ArrayDemo2.cs***





Structures

It is a composite data type consisting of a number of elements of other types. It is similar to a class in many ways. It can contain constructors, fields methods, etc. It cannot implement inheritance. Cannot have a parameterless constructor.

***StructDemo.cs***







Enumerations

Are a set of named constants. First element of the enum is assigned a value of 0 and is incremented for each subsequent enum element. Default value can be overridden.

***EnumDemo.cs***





Classes

It is a data structure that may contain data members(fields,methods and events). They support inheritance. Members of a class are either static or instance members. Instance members belong to objects(instances of a class).

***ClassDemo.cs***



Static Constructors

A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or any static members are referenced. Cannot have any parameters.

***StaticConst.cs***





Destructors

A destructor is called by the garbage collector. The garbage collector frees memory by destroying objects that are no longer required or referenced.

·       They cannot be used with structures.

·       A class can have only one destructor.

·       They cannot be initialized or overloaded.

·       They cannot be called. They are invoked automatically.
The programmer has no control on when the destructor is called because this is determined by the garbage collector. The garbage collector checks for objects that are no longer being used by the application. It considers these objects eligible for destruction and reclaims their memory. Destructors are also called when the program exits.
The destructor implicitly calls the Object.Finalize method on the object's base class. Therefore, the destructor code is implicitly translated to:

protected override void Finalize()
 
The Finalize method is called recursively for all of the instances in the inheritance chain, from the most derived to the least derived.
If your application is using an expensive external resource, it is also recommended that you provide a way to explicitly release the resource before the garbage collector frees the object. You do this by implementing a Dispose method (from the IDisposable interface) that performs the necessary cleanup for the object. This can considerably improve the performance of the application. Even with this explicit control over resources, the destructor becomes a safeguard to clean up resources if the call to the Dispose method failed.

***DestDemo.cs***





Method Overloading

Can be implemented by:

1.  Specifying different number of parameters.

2.  Specifying different types of parameters.

***MethodOverloadDemo.cs***



Operator Overloading

Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type.



The comparison operators, if overloaded, must be overloaded in pairs; that is, if == is overloaded, != must also be overloaded. The reverse is also true, and similar for < and >, and for <= and >=.





Operators that can be overloaded:

+ -  * / % ++ --  < > <= >= <>……

***OperatorOverload1.cs***





Inheritance

***Inht1.cs***

***Inht2.cs***





Sealing A Class

You can seal a class when you don’t want any class to

inherit from a class.

***SealedClass.cs***







Method Overriding

To override an existing method of the base class, declare a

new method in the derived class with the same name and

prefix it with the new keyword.

***MethodOverride.cs***





Virtual Functions

Are useful for calling derived class method from an object of the base class.

***VirtualDemo1.cs***

 


Abstrcat Base Classes


Contain only method definitions. The actual implementations of the methods is done only in the derived classes.

***AbstractDemo.cs***





Interfaces


It is similar to a pure abstract class. It can contain only abstract methods and no implementations.

A class can implement an interface and can also inherit from a class.

A class can also implement more than one interface.

***Interface1.cs***



Explicit interface implementation allows the programmer to inherit two interfaces that share the same member names and give each interface member a separate implementation. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.

***Interface2.cs***





Passing parameters to methods

In C#, parameters can be passed either by value or by reference. Passing parameters by reference allows function members (methods, properties, indexers, operators, and constructors) to change the value of the parameters and have that change persist. To pass a parameter by reference, use the ref or out keyword.

***params1.cs***





Output parameters
A parameter declared with an out modifier is an output parameter. Similar to a reference parameter, an output parameter does not create a new storage location. Instead, an output parameter represents the same storage location as the variable given as the argument in the method invocation.
Output parameters are typically used in methods that produce multiple return values.

***params2.cs***



params keyword
The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.
No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

***params3.cs***

Properties


Provide facility to protect field in a class by reading and writing to it. With properties, you just have to define the set/get methods and continue using the data members as fields. The runtime takes care of identifying and calling the appropriate get/set function.



Types of properties


1.  Read/Write: Contains the get and set accessor methods. Provides

read and write access to data members.

2.  Read-Only: Contains only a get accessor.

3.  Write-Only: Contains only a set accessor.



ü Properties are logical fields.

ü Properties are an extension of fields.

ü Unlike fields, properties do not correspond directly to a storage location.

ü Properties do not use parentheses.

***PropDemo.cs***



Indexers

Are created for arrays so that the elements are accessed directly by specifying the index from the class object. Allow an object to be indexed in the same way as an array.



<accessmodifier> <return type> this [<datatype> <varname>]

***Indexer1.cs***



·           Indexers do not point to any memory locations.

·           Indexers can have non-integer subscripts(indexes).

·           Indexers can be overloaded.

***Indexer2.cs***

Multiple Parameters


***Indexer3.cs***



Delegates

Contain a reference to a method. Helps you to decide which method to call at runtime. Can invoke either an instance method or a static method.

Steps:

1.  Define a delegate

2.  Instantiate a delegate

3.  Use the delegate



public delegate <return type> <delegatename>(<args>);

***Delegate1.cs***



Multicasting

Is the ability to create an invocation list or a chain of methods that will be automatically called when a delegate is invoked. A delegate that will make use of multicasting will usually have a void return type.

***MultiCastDemo.cs***





Events

An event is an automatic notification that some action has occurred. An object that has an interest in an event registers an event handler for that event. When the event occurs, all registered handlers are called. Event handlers are represented by delegates.

event <event-delegate object name>;



***EventDemo.cs***






No comments:

Post a Comment

C# LINQ Joins With SQL

There are  Different Types of SQL Joins  which are used to query data from more than one database tables. In this article, you will learn a...