Saturday, 29 September 2012

Common Type System (C# Programming Language)


C# has a unified type system. This unified type system is called Common Type System (CTS).

A unified type system implies that all types, including primitives such as integers, are sub-classes of the System.Object class. For example, every type inherits a  ToString() method.


Categories of data types


CTS separates data types into two categories:
• Value types
• Reference types

Instances of value types do not have referential identity nor referential comparison semantics - equality and inequality comparisons for value types compare the actual data values within the instances, unless the corresponding operators are overloaded. Value types are derived from System.ValueType, always have a default value, and can always be created and copied. Some other limitations on value types are that they cannot derive from each other (but can implement interfaces) and cannot have an explicit default (parameterless) constructor. Examples of value types are all primitive types, such as int (a signed 32-bit integer), float (a 32-bit IEEE floating-point number), char (a 16-bit Unicode code unit), and System.DateTime (identifies a specific point in time with nanosecond precision). Other examples are enum (enumerations) and struct (user defined structures).

In contrast, reference types have the notion of referential identity - each instance of a reference type is inherently distinct from every other instance, even if the data within both instances is the same. This is reflected in default equality and inequality comparisons for reference types, which test for referential rather than structural equality, unless the corresponding operators are overloaded (such as the case for System.String). In general, it is not always possible to create an instance of a reference type, nor to copy an existing instance, or perform a value comparison on two existing instances, though specific reference types can provide such services by exposing a public constructor or implementing a corresponding interface (such as ICloneable or IComparable). Examples of reference types are object (the ultimate base class for all other C# classes), System.String (a string of Unicode characters), and System.Array (a base class for all C# arrays).
Both type categories are extensible with user-defined types.


Boxing and Unboxing



Boxing is the operation of converting a value-type object into a value of a corresponding reference type. Boxing in C# is implicit.

Unboxing is the operation of converting a value of a reference type (previously boxed) into a value of a value type. Unboxing in C# requires an explicit type cast. A boxed object of type T can only be unboxed to a T (or a nullable T).

For Example :

int foo = 42;// Value type.
object bar = foo;     // foo is boxed to bar.
int foo2 = (int)bar;  // Unboxed back to value type.

Generics

Generics were added to version 2.0 of the C# language. Generics use type parameters, which make it possible to design classes and methods that do not specify the type used until the class or method is instantiated. The main advantage is that one can use generic type parameters to create classes and methods that can be used without incurring the cost of runtime casts or boxing operations.

For Example:

// Declare the generic class.
 
public class GenericList<T>
{
    void Add(T input) { }
}
 
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int.
        GenericList<int> list1 = new GenericList<int>();
 
        // Declare a list of type string.
        GenericList<string> list2 = new GenericList<string>();
 
        // Declare a list of type ExampleClass.
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
    }
}

Friday, 28 September 2012

Distinguishing features of C# Programming Language


C# is the programming language that most directly reflects the underlying Common Language Infrastructure (CLI).Most of its intrinsic types correspond to value-types implemented by the CLI framework. However, the language specification does not state the code generation requirements of the compiler: that is, it does not state that a C# compiler must target a Common Language Runtime, or generate Common Intermediate Language (CIL), or generate any other specific format. Theoretically, a C# compiler could generate machine code like traditional compilers of C++ or Fortran.

Some notable features of C# that distinguish it from C and C++ (and Java, where noted) are:

  • It has no global variables or functions. All methods and members must be declared within classes. Static members of public classes can substitute for global variables and functions.
  • Local variables cannot shadow variables of the enclosing block, unlike C and C++.
  • C# supports a strict Boolean data type, bool. Statements that take conditions, such as while and if, require an expression of a type that implements the true operator, such as the boolean type. While C++ also has a boolean type, it can be freely converted to and from integers, and expressions such as if(a) require only that a is convertible to bool, allowing a to be an int, or a pointer. C# disallows this "integer meaning true or false" approach, on the grounds that forcing programmers to use expressions that return exactly bool can prevent certain types of common programming mistakes in C or C++ such as if (a = b) (use of assignment = instead of equality ==).
  • In C#, memory address pointers can only be used within blocks specifically marked as unsafe, and programs with unsafe code need appropriate permissions to run. Most object access is done through safe object references, which always either point to a "live" object or have the well-defined null value; it is impossible to obtain a reference to a "dead" object (one that has been garbage collected), or to a random block of memory. An unsafe pointer can point to an instance of a value-type, array, string, or a block of memory allocated on a stack. Code that is not marked as unsafe can still store and manipulate pointers through the System.IntPtr type, but it cannot dereference them.
  • Managed memory cannot be explicitly freed; instead, it is automatically garbage collected. Garbage collection addresses the problem of memory leaks by freeing the programmer of responsibility for releasing memory that is no longer needed.
  • In addition to the try...catch construct to handle exceptions, C# has a try...finally construct to guarantee execution of the code in the finally block, whether an exception occurs or not.
  • Multiple inheritance is not supported, although a class can implement any number of interfaces. This was a design decision by the language's lead architect to avoid complication and simplify architectural requirements throughout CLI.
  • C#, like C++, but unlike Java, supports operator overloading.
  • C# is more type safe than C++. The only implicit conversions by default are those that are considered safe, such as widening of integers. This is enforced at compile-time, during JIT, and, in some cases, at runtime. No implicit conversions occur between booleans and integers, nor between enumeration members and integers (except for literal 0, which can be implicitly converted to any enumerated type). Any user-defined conversion must be explicitly marked as explicit or implicit, unlike C++ copy constructors and conversion operators, which are both implicit by default. Starting with version 4.0, C# supports a "dynamic" data type that enforces type checking at runtime only.
  • Enumeration members are placed in their own scope.
  • C# provides properties as syntactic sugar for a common pattern in which a pair of methods, accessor (getter) and mutator (setter) encapsulate operations on a single attribute of a class. No redundant method signatures for the getter/setter implementations need be written, and the property may be accessed using attribute syntax rather than more verbose method calls.
  • Checked exceptions are not present in C# (in contrast to Java). This has been a conscious decision based on the issues of scalability and versionability.
  • Though primarily an imperative language, since C# 3.0 it supports functional programming techniques through first-class function objects and lambda expressions.

Version of C# Programming Language





In the course of C# Programming Language development, the C# language has gone through several versions.



The course of its development is shown in the tabular format:

VersionLanguage specificationDate.NET FrameworkVisual Studio
ECMA*ISO/IEC**Microsoft
C# 1.0December 2002April 2003January 2002January 2002.NET Framework 1.0Visual Studio .NET 2002
C# 1.2October 2003April 2003.NET Framework 1.1Visual Studio .NET 2003
C# 2.0June 2006September 2006September 2005November 2005.NET Framework 2.0Visual Studio 2005
C# 3.0NoneAugust 2007November 2007
.NET Framework 2.0 (Except LINQ/Query Extensions)
.NET Framework 3.0 (Except LINQ/Query Extensions)
.NET Framework 3.5
Visual Studio 2008
Visual Studio 2010
C# 4.0April 2010April 2010.NET Framework 4Visual Studio 2010
C# 5.0N/AAugust 2012.NET Framework 4.5Visual Studio 2012


*ECMA International is an international, private (membership-based) non-profit standards organization for information and communication systems. It acquired its current name in 1994, when the European Computer Manufacturers Association (ECMA) changed its name to reflect the organization's global reach and activities. As a consequence, the name is no longer considered an acronym and no longer uses full capitalization.

**ISO/IEC JTC 1 is Joint Technical Committee 1 of the International Organization for Standardization (ISO) and the International Electrotechnical Commission (IEC). It deals with all matters of information technology. 
It was formed in 1987 as a merger between ISO/TC 97 (Information Technology) and IEC/TC 83, with IEC//SC 47B joining later. The intent was to bring together in a single Committee the Information Technology standardization activities of the two parent organizations.




The Microsoft C# 2.0 specification document only contains the new 2.0 features. For older features use the 1.2 specification above. No ECMA or ISO/IEC specifications exist for C# 3.0, 4.0 or 5.0.


Summary of Versions of C# Programming Language:

C# 2.0C# 3.0C# 4.0C# 5.0 Future
Features
added
  • Generics
  • Partial types
  • Anonymous methods
  • Iterators
  • Nullable types
  • Private setters (properties)
  • Method group conversions (delegates)
  • Implicitly typed local variables
  • Object and collection initializers
  • Auto-Implemented properties
  • Anonymous types
  • Extension methods
  • Query expressions
  • Lambda expressions
  • Expression trees
  • Partial Methods
  • Dynamic binding
  • Named and optional arguments
  • Generic co- and contravariance
  • Embedded interop types ("NoPIA")
  • Asynchronous methods
  • Caller info attributes
  • Compiler-as-a-service("Roslyn")

Thursday, 27 September 2012

History of C# Programming


During the development of the .NET Framework, the class libraries were originally written using a managed code compiler system called Simple Managed C (SMC). In January 1999, Anders Hejlsberg formed a team to build a new language at the time called Cool, which stood for "C-like Object Oriented Language". Microsoft had considered keeping the name "Cool" as the final name of the language, but chose not to do so for trademark reasons. By the time the .NET project was publicly announced at the July 2000 Professional Developers Conference, the language had been renamed C#, and the class libraries and ASP.NET runtime had been ported to C#.


C#'s principal designer and lead architect at Microsoft is Anders Hejlsberg, who was previously involved with the design of Turbo PascalEmbarcadero Delphi (formerly CodeGear Delphi and Borland Delphi), and Visual J++. In interviews and technical papers he has stated that flaws in most major programming languages (e.g. C++JavaDelphi, and Smalltalk) drove the fundamentals of the Common Language Runtime (CLR), which, in turn, drove the design of the C# language itself.
James Gosling, who created the Java programming language in 1994, and Bill Joy, a co-founder of Sun Microsystems, the originator of Java, called C# an "imitation" of Java; Gosling further claimed that "[C# is] sort of Java with reliability, productivity and security deleted." Klaus Kreft and Angelika Langer (authors of a C++ streams book) stated in a blog post that "Java and C# are almost identical programming languages. Boring repetition that lacks innovation," "Hardly anybody will claim that Java or C# are revolutionary programming languages that changed the way we write programs," and "C# borrowed a lot from Java - and vice versa. Now that C# supports boxing and unboxing, we'll have a very similar feature in Java." Anders Hejlsberg has argued that C# is "not a Java clone" and is "much closer to C++" in its design.
Since the release of C# 2.0 in November of 2005, the C# and Java languages have evolved on increasingly divergent trajectories, becoming somewhat less similar. One of the first major departures came with the addition of generics to both languages, with vastly different implementations. C# makes use of reification to provide "first-class" generic objects that can be used like any other class, with code generation performed at class-load time. By contrast, Java's generics are essentially a language syntax feature, and they do not affect the generated byte code because the compiler performs type erasure on the generic type information after it has verified its correctness.
Furthermore, C# has added several major features to accommodate functional-style programming, culminating in their LINQ extensions released with C# 3.0 and its supporting framework of lambda expressionsextension methods, and anonymous classes. These features enable C# programmers to use functional programming techniques, such as closures, when it is advantageous to their application. The LINQ extensions and the functional imports help developers reduce the amount of "boilerplate" code that is included in common tasks like querying a database, parsing an xml file, or searching through a data structure, shifting the emphasis onto the actual program logic to help improve readability and maintainability.
C# used to have a mascot called Andy (named after Anders Hejlsberg). It was retired on 29 Jan 2004.