Thursday, June 20, 2013

Command Line Arguments

Command line arguments are parameters supplied to the Main method at the time of invoking it for execution. To understand the concepts see the example given below:

Program of Command line argument to accept name from the command line and writes to the console.

using System;
class sample
{
       public static void Main( string[ ] args)
  {
       console.write("welcome to");
       console.write(" " +args[0]);
       console.write(" " +args[l]);
  }
}

Execution for this program
C:\ > Sample My Home
Output of Example
Welcome to My Home

In Previous examples, we have used the Main method with no parameters. Notice that in the above example how the Main is declared.
Main is declared with a parameters args. The parameter args is an array of strings. Any arguments provided in the command line at the time of execution, are passed to the array args as its elements. We can access the array elements by using a subscript like args[0], args[1] and so on.

Wednesday, June 19, 2013

Identifiers and Variables

Identifiers refer to the names of variables, functions arrays, classes, etc. created by programmer. They are fundamental requirement of any language. Each language has its own rules for naming these identifiers.
To name the variables of your program, you must follow strict rules. In fact, everything else in your program must have a name.
There are some rules you must follow when naming your objects. On this site, here are the rules we will follow:

• The name must start with a letter or an underscore or the at symbol @.

• After the first letter or underscore, the name can have letters, digits, and/or underscores.

• The name must not have any special characters other than the underscore.

• The name cannot have a space.

• It should not a keyword.

C# is case-sensitive. This means that the names Case, case, and CASE are completely different. For example, the main function is always written Main.

Sunday, June 16, 2013

Boxing and Unboxing in C#

Boxing

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 of a value allocated an object instance and copies the values 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 variables:
Object o = i;

The result of this statement is creating an object, 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 0 is illustrated in the following figure.
Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type.
It also possible, but never needed to perform the boxing explicitly as in the following example

Int i = 123;
Object O = (object) i;

Unboxing

Unboxing is an explicit conversion from the object to 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 it is a boxed value of the given value type.
• Copying the value from the instance into the value-type variable.

The following statements demonstrate both boxing and unboxing operations:
Int i = 123;       // a value type
Object O = i;   //boxing
int j = (int) O;   // unboxing

Unboxing is an explicit conversion from the object to value type or from an interface type to a value type that implements the interface.

For the unboxing of value types to succeed at runtime, 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 or a reference to an incompatible value type will return an invaIidcastException.

Saturday, June 15, 2013

C# Data Types

C# is a type-safe language Variables are declared as being of a particular type and each variable is constrained to hold only values of its declared type.
Variables can hold either value types or reference types, or they can be pointers. Here's a quick recap of the difference between value types and reference types.

• Where a variable v contains a value type, it directly contains an object with some value. No other variable v' can directly contain the object contained by v (although v' might contain an object with the same value).

• Where a variable v contains a reference type, what it directly contains is something which refers to an object. Another variable v' can contain a reference to the same object referred to by v.

Value Types

C# defines the following value types:

    Primitives int i;
    Enum enum state {off, on }
    Struct struct Point{int x, y; }

It is possible in C# to define your own value types by declaring enumerations or structs. These user-defined types are mostly treated in exactly the same way as C#'s predefined value types, although compilers are optimized for the latter. In C# all of the apparently fundamental value types are in fact built up from the (actually fundamental) object type.

Reference Types

The pre-defined reference types are object and string, where object - is the ultimate base class of all other types. New reference types can be defined using 'class', 'interface', and 'delegate' declarations. Therefore the reference types are:

  1. Predefined Reference Types
• Object                          • String

  1. User Defined Reference Types
• Classes                      • Interfaces
• Delegates                  • Arrays

Reference types actually hold the value of a memory address occupied by the object they reference.

Friday, June 14, 2013

Features of C#

Simplicity

All the Syntax of java is like C++. There is no preprocessor and much larger library. C# code does not require header files. All code is written inline.

Consistent Behavior

C# introduced a 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 simply and easily.

Modern Programming Language

C# supports number of modem features, such as:
• Automatic Garbage Collection
• Error handling features
• Modern debugging features
• Robust Security features

Pure Object-Oriented Programming Language

In C#, everything is an object. There are no more global functions, variable and constants. It supports all three object oriented features:
• Encapsulation
• Inheritance
• Polymorphism

Type Safety

Type safety promotes robust programming. Some examples of type safety are:
• All objects and arrays are initialized by zero dynamically
• An error message will be produced, on use of any uninitialized variable
• Automatic checking of array (out of bound and etc.)

Feature of Versioning

Making new versions of software module work with the existing applications is known as versioning. It is achieved by the keywords new and override.

Compatible with other Language

C# enforces the .NET common language specifications (CLS) and therefore allows interoperation with other .NET language.

Inter-operability

Language interoperability is the ability of code to interact with code that is written using a different programming language. Language interoperability can help maximize code reuse and, therefore, improve the efficiency of the development process. C# provides support for using COM objects, no matter what language was used to author them. C# also supports a special feature that enables a program to call out any native API.

Wednesday, June 12, 2013

Introduction to C#

Microsoft Corporation developed a new computer programming language C# pronounced as 'C- Sharp'. C# is a simple, modem, object oriented, and type safe programming language derived from C and C++. C# is a purely object-oriented language like as Java. It has been designed to support the key features of .NET framework. Like Java, C# is a descendant language of C++ which is descendant of C language.
C# modernizes C++ by enhancing some of its features and adding a few new features. C# borrows Java's features such as grouping of classes, interface and implementation together in one file so the programmers can easily edit the codes. C# also handles objects using reference, the same way as Java.

Comparing C# to C++ and Java

C# and Java are both new-generation languages descended from a line including C and C++. Each includes advanced features, like garbage collection, which remove some of the low level maintenance tasks from the programmer. In a lot of areas they are syntactically similar.
Both C# and Java compile initially to an intermediate language: C# to Microsoft Intermediate Language (MSIL), and Java to Java byte code. In each case the intermediate language can be run - by interpretation or just-in-time compilation on an appropriate 'virtual machine'. In C#, however, more support is given for the further compilation of the intermediate language code into native code. C# contains more primitive data types than Java, and also allows more extension to the value types. For example, C# supports 'enumerations', type-safe value types which are limited to a defined set of constant variables, and 'structs', which are user-defined value types.

Unlike Java, C# has the useful feature that we can overload various operators.
Like Java, C# gives up on multiple class inheritance in favor of a single inheritance model extended by the multiple inheritances of interfaces. However, polymorphism is handled in a more complicated fashion; with derived class methods either 'overriding' or 'hiding' super class methods
C# also uses 'delegates'-type-safe method pointers. These are used to implement event handling.

C# versus C++

Although it has some elements derived from Visual Basic and Java, C++ is C#'s closest relative. In an important change from C++, C# code does not require header files. All code is written inline.
As touched on above, the .NET runtime in which C# runs performs memory management, taking care of tasks like garbage collection. Because of this, the use of pointers in C# is much less important than in C++. Pointers can be used in C#, where the code is marked as 'unsafe', but they are only really useful in situations where performance gains are at an absolute premium.
Speaking generally, the 'plumbing' of C# types is different from that of C++ types, with all C# types being ultimately derived from the 'object' type. For instance, C# arrays are bounds checked unlike in C++, and it is therefore not possible to write past the end of a C# array.
C# statements are quite similar to C++ statements. To note just one example of a difference: the 'switch' statement has been changed so that 'fall-through' behavior is disallowed.

        As mentioned above, C# gives up on the idea of multiple class inheritance. Other differences relating to the use of classes are: there is support for class 'properties' of the kind found in Visual Basic, and class methods are called using the Operator rather than the :: operator.

Monday, June 10, 2013

Reflection

.NET Framework's Reflection API allows you to fetch type (assembly) information at runtime programmatically. We can also achieve late binding by using .NET Reflection. At runtime, the Reflection mechanism uses the PE file to read information about the assembly. Reflection enables you to use code that is not available at compile time. .NET Reflection allows an application to collect information about itself and also to manipulate on itself. It can be used effectively to find all types in an assembly and/or dynamically invoke methods in an assembly. This includes information about the type, properties, methods, and events of an object. With Reflection, we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. We can also access attribute information using Reflection.
Using Reflection, you can get any kind of information which you can see in a class viewer; for example, information on the methods, properties, fields, and events of an object.
The System.Reflection namespace and the System.Type class plays a very important role in .NET Reflection. These two work together and allow you to reflect over many other aspects of a type.

Sunday, June 9, 2013

HOW CLR PROVIDES CROSS LANGUAGE INTERACTION

A component can be called by any .NET-based language regardless the original language of that component. The cross-language compatibility is possible because objects created in different .NET languages agree on a common set of types and features. These common types and features are spelled out in the Common Language Specification (CLS).
Let’s take a look how CLR provide cross language interaction:

1. Every .NET based language compiler translates source language program into MSIL code.
2. The CLR also defines, the format' of storing assembly metadata and this means all assemblies whatever language they were written in, share a common format for storing Metadata. '
3. All .NET based language follow Common Language Specification (CLS). CLS specifies a set of features that every .NET complaint language has to follow. A .NET complaint language may have its own unique features but it must follow the common set of features specified in CLS.

Because the target code of each .NET based compiler is represented in same language. The metadata is expressed in same language 'and all sources language confirms to follow a set of features so the codes written in two different languages can interoperate.

Saturday, June 8, 2013

Common Language Infrastructure (CLI)

The Common Language Infrastructure (CLI) is an open specification developed by Microsoft that describes the executable code and runtime environment that allows multiple high-level languages to be used on different computer platforms without being rewritten for specific architectures. CLR is Microsoft Commercial implementation of Common Language Infrastructure (CLI).


       The Common Language Infrastructure (CLI) is a theoretical model of a development platform that provides a device and language independent way to express data and behavior of applications.


While the CLI primarily supports Object Oriented Programming (OOP) languages, procedural and functional languages are also supported. Through the CLI, languages can interoperate with each other and make use of a built-in garbage collector, security system, exception support, and a powerful framework.

Thursday, June 6, 2013

Garbage Collection

When you initialize a variable using the new operator, you are in fact asking the compiler to provide you some memory space in the heap memory. The compiler is said to "allocate" memory for your variable. When that variable is no longer needed, such as when your program closes, it (the variable) must be removed from memory and the space it was using can be made available to other variables or other programs. This is referred to as garbage collection. In the past, namely in C/C++, this was a concern for programmers because they usually had to remember to manually delete such a variable (a pointer) and free its memory.

The .NET Framework solves the problem of garbage collection by letting the compiler "clean" memory after you. This is done automatically when the compiler judges it necessary so that the programmer doesn't need to worry about this issue.

Garbage collection is a mechanism that allows the computer to detect when an object can no longer is accessed. It then automatically releases the memory used by that object (as well as calling a clean-up routine, called a "finalizer" which is written by the user). Some garbage collectors like the one used by .NET, compact memory and therefore decrease your program's working set.

For most programmers, having a garbage collector (and using garbage collected objects) means that you never have to worry about deallocating memory, or reference counting objects, even if you use sophisticated data structures. It does require some changes in coding style, however, if you typically de-allocate system resources (file handles, locks, and so forth) in the same block of code that releases the memory for an object. With a garbage collected object you should provide a method that releases the system resources deterministically (that is, under your program control) and let the garbage collector release the memory: when it compact the working set.

Wednesday, June 5, 2013

Just in Time Compiler (JIT)

Machines cannot run MSIL directly. JIT compiler turns MSIL into native code, which is CPU specific code that runs on the same computer architecture as the JIT compiler. Because the common. Language runtime supplies a JIT compiler for each supported CPU architecture, developers can write a set of MSIL that can be JIT-compiled and run on computers with different architectures.
However, your managed code will run only on a specific operating system if it calls platform specific native APIs, or a platform-specific class library.

JIT compilation takes into account the fact that some code might never get called during execution. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as needed during execution and stores the resulting native code so that it is accessible for subsequent calls.

The loader creates and attaches a stub to each of a type's methods when the type is loaded. On the initial call to the method, the stub passes control to the JIT compiler, which converts the MSIL for that method into native code and modifies the stub to direct execution· to the location of the native code. Subsequent calls of the JIT -compiled method proceed directly to the native code that was previously generated, reducing the time it takes to JIT-compile and run the code.

Managed and Unmanaged Code

Managed code is code that is written to target the services of the common language runtime. In order· to target these services, the code must provide a minimum level of information (metadata) to the runtime. All C#, Visual Basic .NET, and JScript .NET code is managed by default. Visual Studio .NET C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/CLR).

Thursday, May 30, 2013

CLR (Common Language Runtime)

Common Language Runtime is the heart of .NET Framework used to manage the program written in .NET Framework compatible language (E.g. C#, Vb.NET, J# etc.). In other words, CLR is Execution Engine which executes the program for .NET Framework.
It provides a number of services, including the following:

ü  Code management (loading and execution)
ü  Application memory isolation
ü  Verification of type safety
ü  Conversion of IL to native code
ü  Access to metadata (enhanced type information)
ü  Managing memory for managed objects
ü  Enforcement of code access security
ü  Exception handling, including cross-language exceptions
ü  Interoperation between managed code, COM objects, and pre-existing DLLs
ü  Automation of object layout
ü  Support for developer services (profiling, debugging, and so on)


The Common Language Runtime (CLR) is the virtual machine component of Microsoft's .NET initiative. It is Microsoft's implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. The CLR runs a form of byte code called the Common Intermediate Language (CIL, previously known as MSIL (Microsoft Intermediate Language)


How CLR Works?


When we write a program in .NET compatible language, then the compiler for C# or VB.NET compiles the code in IL (Intermediate Language) or MSIL (Microsoft Intermediate Language) and then IL will be the input of CLR's component Just in Time compiler to produce machine independent code.
Apart from the above CLR is also responsible for:

Memory management

Thread management

Exception handling

Garbage collection

Security





Wednesday, May 29, 2013

CTS (Common Type System) & MSIL

Common Type System is the part of .NET Framework built in with CLR which is responsible for defining, managing different language's operation supported by .NET Framework. CTS are responsible for cross language Integration (Means you can have a dll which is written in C# and to be used in VB.Net application) and Type Safety. It enforces a set of rules that a programming language must follow.


Types of CTS (Common Type System)

The common type system supports two general categories of types:

1. Value types

Value types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be built-in, user-defined or enumerations types.

2. Reference types

Reference types stores a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointers types, or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types are user-defined classes, boxed value types, and delegates.



CTS, much like Java, define every data type as a Class. Every .NET compliant language must stick to this definition. Since CTS defines every data type as a class; this means that only Object-Oriented (or Object-Based) languages can achieve .NET compliance.


Microsoft Intermediate Language (MSIL)


A .NET programming language (C#, VB.NET, J# etc.) does not compile into executable code; instead it compiles into an intermediate code called Microsoft Intermediate Language (MSIL). As a programmer one need not worry about the syntax of MSIL - since our source code in automatically converted to MSIL. The MSIL code is then send to the CLR (Common Language Runtime) that converts the code to machine language which is then run on the host machine. MSIL is similar to Java Byte code. A Java program is compiled into Java Byte code (the .class file) by a Java compiler, the class file is then sent to JVM which converts it into the host machine language.

Tuesday, May 28, 2013

Common Language Specification (CLS)

One of the obvious themes of .NET is unification and interoperability between various programming languages. In order to achieve this; certain rules must be laid and all the languages must follow these rules. In other words we cannot have languages running around creating their own extensions and their own fancy new data types. CLS is the collection of the rules and constraints that every language (that seeks to achieve .NET compatibility) must follow.
The Common Language Specification is a set of basic language features (constructs and constraints) that serves as a guide for library writers and compiler writers. It allows libraries to be fully usable from any language supporting the CLS, and for those languages to integrate with each other. The Common Language Specification is a subset of the common type system. The CLS is actually a set of restrictions on the CTS. The CLS defines not only the types allowed in external calls, but the rules for using them, depending on the goal of the user.
Informally CLS is a simply a contract between programming language designers and class library authors. The CLS is basically just a subset of the entire set of features supported by the CLR. The CLS includes things such as calling virtual methods, overloading methods and does not include things such as unsigned types. CLS is weighted very heavily in favor of the library designers.
The Common Language Specification describes a common level of language functionality. The CLS is a set of rules that a language compiler must adhere to in order to create .NET applications that run in the CLR. Anyone who wants to write a .NET·-compliant compiler needs simply to adhere to these rules and that's it. The relatively high minimum bar of the CLS enables the creation of a club of CLS-compliant languages. Each member of this club enjoys dual benefits: complete access to .NET framework functionality and rich interoperability with other compliant languages. For example a VB class can inherit from a C# class and override its virtual methods.

The common language specification (CLS) is a collection of rules and restrictions that allow interoperation between languages. Even though the CLI does not require compilers to follow CLS, code that follows the CLS rules is compatible with all other languages that follow the CLS rules.
Microsoft has defined three level of CLS compatibility/compliance. The goals and objectives of each compliance level have been set aside. The three compliance levels with their brief description are given below:

  1. Compliant producer
The component developed in this type of language can be used by any other language.

  1. Consumer
The language in this category can use classes produced in any other language. In simple words this means that the language can instantiate classes developed in other language. 

  1. Extender
Languages in this category cannot just use the classes as in CONSUMER category; but can also extend classes using inheritance. Languages that come with Microsoft Visual Studio namely Visual C++, Visual Basic and C#; all satisfy the above three categories. Vendors can select any of the above categories as the targeted compliance level(s) for their languages.

Monday, May 27, 2013

UNIFIED CLASSES (Base Class Library)

The Unified Classes (Base Class Library) is a set of classes that provide useful functionality to CLR programmers. The .NET Framework class library exposes features of the runtime and simplifies the development of .NET-based applications. In addition, developers can extend classes by creating their own libraries of classes. All applications (Web, Windows, and XML Web services) access the same .NET Framework class libraries, which are held in namespaces. All .NET-based languages also access the same libraries.

The run time is responsible for managing your code and providing services to it while it executes, playing a role similar to that of the Visual Basic 6.0 run time.
The .NET programming languages including Visual Basic .NET, Microsoft Visual C# and C++ managed extensions and many other programming languages from various vendors utilize .NET services and features through a common set of unified classes.

The .NET unified classes provide foundation of which you build your applications, regardless of the language you use. Whether you simply concating a string, or building a windows Services or a multiple-tier web-based applications, you will be using these unified classes.
The unified classes provide a consistent method of accessing the platforms functionality. Once you learn to use the class library, you'll find that all tasks follow the same uniform architecture, you no longer need to learn and master different API architecture to write your applications.
By building your applications on a unified, integrated framework, you maximize your return on the time you spend learning this framework, and you end up with more robust applications that are easy to deploy and maintain.


Class Libraries

The .NET Framework has an extensive set of class libraries. This includes classes for:

• Data Access: High Performance data· access classes for connecting to SQL Server or any other OLEDB provider.
• XML Supports: Next generation XML support that goes far beyond the functionality of MSXML.
• Directory Services: Support for accessing Active directory/LDPA using ADSI.
• Regular Expression: Support for above and beyond that found in Perl 5.
• Queuing Supports: Provides a clean object-oriented set of classes for working with MSMQ.
These class libraries use the CLR base class libraries for common functionality.

Saturday, May 25, 2013

Introduction to .NET Framework

The .NET Framework is the heart of Microsoft .NET. The .NET Framework is a software development platform of Microsoft .NET. Like any platform, it provides a run-time, defines functionality in some libraries, and supports a set of programming languages. The .NET Framework provides the necessary compile-time and run-time foundation to build and run .NET-based applications.

Components of .NET Framework:


The .NET Framework consists of:

• Common Language Runtime
• Class Libraries
• Support for Multiple Programming Language


Application Development and Execution





  1. Developing application:
Since Microsoft .NET is a Multilingual platform then any.NET based language can be chosen to develop applications. Comfort ability of application programmers, specific requirement of applications may be the major factors in selection of language.


  1. Choosing a Compiler
According to the language we can choose its run time aware compiler for .NET platform. Because it is a Multilanguage execution environment, the runtime supports a wide variety of data types and language features.


  1. Compiling to MSIL
When compiling your source code, the compiler translates it into an intermediate code represented in Microsoft intermediate language (MSIL). Before code can be run, MSIL code must be converted to CPU-specific code, usually by a just-in-time (JIT) compiler. When a compiler produces MSIL, it also produces metadata. Metadata includes following information.
• Description of the types in your code, including the definition of each type,
• The signatures of each type's members,
• The members that your code references,
• Other data that the runtime uses at execution time.
The MSIL and metadata are contained in a portable executable (PE) file that is based on and extends the published Microsoft PE and common object file format (COFF) used historically for executable content. This file format, which accommodates MSIL or native code as well as metadata, enables the operating system to recognize common language runtime images.


  1. JIT Compilation to Native code:
The MSIL code is compiled into native code by component of CLR named JIT Compiler. JIT compiler intelligently guesses and compiles the intermediate code on piece by piece basis. This piece may be a method or a set of methods. Before a method can be run, it must be compiled to processor-specific code. Each method for which Microsoft intermediate language (MSIL) has been generated is just-in-time-compiled (JIT-compiled) when it is called for the first time, and then run. The next time the method is run, the existing JIT -compiled native code is run. The process of JIT -compiling and then executing the code is repeated until execution is complete.


  1. Type Safety Checking:
As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code is type safe, which means that it only accesses the memory locations it is authorized to access. Additionally, verification inspects code to determine whether the MSIL has been correctly generated, because incorrect MSIL can lead to a violation of the type safety rules. If type-safe code is required by security policy and the code does not pass verification, an exception is thrown when the code is run.


  1. Code execution under CLR:
The common language runtime is responsible for providing following low-level execution services, such as garbage collection, exception handling, security services, and runtime type safety checking. Because of the common language runtime's role in managing execution, programs that target the .NET Framework are sometimes called "managed" applications.


Features of .NET Framework

• It is a platform neutral framework.
• It is a layer between the operating system and the programming language.
• It supports many programming languages, including VB.NET, C# etc.
• .NET provides a common set of class libraries, which can be accessed from any .NET based programming language. There will not be separate set of classes and libraries for each language. If you know anyone .NET language, you can write code in any .NET language.
• In future versions of Windows, .NET will be freely distributed as part of operating system and users will never have to install .NET separately.