C Sharp 2.0

Last updated

The computer programming language, C#, introduces several new features in version 2.0 (corresponding to the 3rd edition of the ECMA-334 standard and the .NET Framework 2.0). These include:

Contents

C# 2.0 Features

Partial class

Partial classes allow implementation of a class to be spread between several files, with each file containing one or more class members. It is useful primarily when parts of a class are generated automatically. For example, the feature is heavily used by code-generating user interface designers in Visual Studio.

file1.cs:

publicpartialclassMyClass{publicvoidMyMethod1(){// Manually written code}}

file2.cs:

publicpartialclassMyClass{publicvoidMyMethod2(){// Automatically generated code}}

Generics

Generics, or parameterized types, or parametric polymorphism is a .NET 2.0 feature supported by C# and Visual Basic. Unlike C++ templates, .NET parameterized types are instantiated at runtime rather than by the compiler; hence they can be cross-language whereas C++ templates cannot. They support some features not supported directly by C++ templates such as type constraints on generic parameters by use of interfaces. On the other hand, C# does not support non-type generic parameters. Unlike generics in Java, .NET generics use reification to make parameterized types first-class objects in the CLI Virtual Machine, which allows for optimizations and preservation of the type information. [1]

Static classes

Static classes are classes that cannot be instantiated or inherited from, and that only allow static members. Their purpose is similar to that of modules in many procedural languages.

Generator functionality

The .NET 2.0 Framework allowed C# to introduce an iterator that provides generator functionality, using a yield return construct similar to yield in Python. [2] With a yield return, the function automatically keeps its state during the iteration.

// Method that takes an iterable input (possibly an array)// and returns all even numbers.publicstaticIEnumerable<int>GetEven(IEnumerable<int>numbers){foreach(intiinnumbers){if(i%2==0)yieldreturni;}}

There is also a yield break statement, in which control is unconditionally returned to the caller of the iterator. There is an implicit yield break at the end of each generator method.

Anonymous delegates

As a precursor to the lambda functions introduced in C# 3.0, C#2.0 added anonymous delegates. These provide closure-like functionality to C#. [3] Code inside the body of an anonymous delegate has full read/write access to local variables, method parameters, and class members in scope of the delegate, excepting out and ref parameters. For example:-

intSumOfArrayElements(int[]array){intsum=0;Array.ForEach(array,delegate(intx){sum+=x;});returnsum;}

Unlike some closure implementations, each anonymous delegate instance has access to the same relative memory location for each bound variable, rather than to the actual values at each creation. See a fuller discussion of this distinction.

Delegate covariance and contravariance

Conversions from method groups to delegate types are covariant and contravariant in return and parameter types, respectively. [4]

The accessibility of property accessors can be set independently

Example:

stringstatus=string.Empty;publicstringStatus{get{returnstatus;}// anyone can get value of this property,protectedset{status=value;}// but only derived classes can change it}

Nullable value types

Nullable value types (denoted by a question mark, e.g. int? i = null;) which add null to the set of allowed values for any value type. This provides improved interaction with SQL databases, which can have nullable columns of types corresponding to C# primitive types: an SQL INTEGER NULL column type directly translates to the C# int?.

Nullable value types received an improvement at the end of August 2005, shortly before the official launch, to improve their boxing characteristics: a nullable variable which is assigned null is not actually a null reference, but rather an instance of struct Nullable<T> with property HasValue equal to false. When boxed, the Nullable instance itself is boxed, and not the value stored in it, so the resulting reference would always be non-null, even for null values. The following code illustrates the corrected flaw:

int?i=null;objecto=i;if(o==null)System.Console.WriteLine("Correct behaviour - runtime version from September 2005 or later");elseSystem.Console.WriteLine("Incorrect behaviour - pre-release runtime (from before September 2005)");

When copied into objects, the official release boxes values from Nullable instances, so null values and null references are considered equal. The late nature of this fix caused some controversy [5] , since it required core-CLR changes affecting not only .NET2, but all dependent technologies (including C#, VB, SQL Server 2005 and Visual Studio 2005).

Null-coalescing operator

The ?? operator is called the null coalescing operator and is used to define a default value for nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand. [6]

objectnullObj=null;objectobj=newObject();returnnullObj??obj;// returns obj

The primary use of this operator is to assign a nullable type to a non-nullable type with an easy syntax:

int?i=null;intj=i??0;// If i is not null, initialize j to i. Else (if i is null), initialize j to 0.

Related Research Articles

In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations.

Generic programming is a style of computer programming in which algorithms are written in terms of data types to-be-specified-later that are then instantiated when needed for specific types provided as parameters. This approach, pioneered by the ML programming language in 1973, permits writing common functions or types that differ only in the set of types on which they operate when used, thus reducing duplicate code.

<span class="mw-page-title-main">D (programming language)</span> Multi-paradigm system programming language

D, also known as dlang, is a multi-paradigm system programming language created by Walter Bright at Digital Mars and released in 2001. Andrei Alexandrescu joined the design and development effort in 2007. Though it originated as a re-engineering of C++, D is a profoundly different language — features of D can be considered streamlined and expanded-upon ideas from C++, however D also draws inspiration from other high-level programming languages, notably Java, Python, Ruby, C#, and Eiffel.

In computer programming, a parameter or a formal argument is a special kind of variable used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are the values of the arguments with which the subroutine is going to be called/invoked. An ordered list of parameters is usually included in the definition of a subroutine, so that, each time the subroutine is called, its arguments for that call are evaluated, and the resulting values can be assigned to the corresponding parameters.

<span class="mw-page-title-main">Pointer (computer programming)</span> Object which stores memory addresses in a computer program

In computer science, a pointer is an object in many programming languages that stores a memory address. This can be that of another value located in computer memory, or in some cases, that of memory-mapped computer hardware. A pointer references a location in memory, and obtaining the value stored at that location is known as dereferencing the pointer. As an analogy, a page number in a book's index could be considered a pointer to the corresponding page; dereferencing such a pointer would be done by flipping to the page with the given page number and reading the text found on that page. The actual format and content of a pointer variable is dependent on the underlying computer architecture.

In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. In some languages, particularly C++, function objects are often called functors.

This article compares two programming languages: C# with Java. While the focus of this article is mainly the languages and their features, such a comparison will necessarily also consider some features of platforms and libraries. For a more detailed comparison of the platforms, see Comparison of the Java and .NET platforms.

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

Many programming language type systems support subtyping. For instance, if the type Cat is a subtype of Animal, then an expression of type Cat should be substitutable wherever an expression of type Animal is used.

<span class="mw-page-title-main">C Sharp (programming language)</span> Programming language

C# is a general-purpose high-level programming language supporting multiple paradigms. C# encompasses static typing, strong typing, lexically scoped, imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines.

Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety". The aspect compile-time type safety was not fully achieved, since it was shown in 2016 that it is not guaranteed in all cases.

In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

Language Integrated Query is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages, originally released as a major part of .NET Framework 3.5 in 2007.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

The programming language C# version 3.0 was released on 19 November 2007 as part of .NET Framework 3.5. It includes new features inspired by functional programming languages such as Haskell and ML, and is driven largely by the introduction of the Language Integrated Query (LINQ) pattern to the Common Language Runtime. It is not currently standardized by any standards organisation.

C# 4.0 is a version of the C# programming language that was released on April 11, 2010. Microsoft released the 4.0 runtime and development environment Visual Studio 2010. The major focus of C# 4.0 is interoperability with partially or fully dynamically typed languages and frameworks, such as the Dynamic Language Runtime and COM.

Windows Runtime (WinRT) is a platform-agnostic component and application architecture first introduced in Windows 8 and Windows Server 2012 in 2012. It is implemented in C++ and officially supports development in C++, Rust/WinRT, Python/WinRT, JavaScript-TypeScript, and the managed code languages C# and Visual Basic .NET (VB.NET).

PL/SQL is Oracle Corporation's procedural extension for SQL and the Oracle relational database. PL/SQL is available in Oracle Database, Times Ten in-memory database, and IBM Db2. Oracle Corporation usually extends PL/SQL functionality with each successive release of the Oracle Database.

Swift is a high-level general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. and the open-source community. Swift compiles to machine code, as it is an LLVM-based compiler. Swift was first released in June 2014, and the Swift toolchain has shipped in Xcode since version 6, released in 2014.

References

  1. "An Introduction to C# Generics". Microsoft. January 2005. Retrieved June 18, 2009.
  2. "yield". C# Language Reference. Microsoft . Retrieved 2009-04-26.
  3. "Anonymous Methods (C#)". C# Programming Guide. Microsoft . Retrieved June 18, 2009.
  4. "Covariance and Contravariance in Delegates (C#)". C# Programming Guide. Microsoft . Retrieved June 18, 2009.
  5. Somasegar (August 11, 2005). "Nulls not missing anymore". Somasegar's WebLog. MSDN . Retrieved 2008-11-05.
  6. "?? Operator". C# Reference. Microsoft . Retrieved 2008-11-23.