C Sharp 4.0

Last updated

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. [1] 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.

Contents

Features

The following new features were added in C# 4.0. [2]

Dynamic member lookup

A new pseudo-type dynamic is introduced into the C# type system. It is treated as System.Object, but in addition, any member access (method call, field, property, or indexer access, or a delegate invocation) or application of an operator on a value of such type is permitted without any type checking, and its resolution is postponed until run-time. This is known as duck typing. For example:

// Returns the value of Length property or field of any objectintGetLength(dynamicobj){returnobj.Length;}GetLength("Hello, world");// a string has a Length property,GetLength(newint[]{1,2,3});// and so does an array,GetLength(42);// but not an integer - an exception will be thrown in GetLength method at run-time

Dynamic method calls are triggered by a value of type dynamic as any implicit or explicit parameter (and not just a receiver). For example:

voidPrint(dynamicobj){System.Console.WriteLine(obj);// which overload of WriteLine() to call is decided at run-time}Print(123);// ends up calling WriteLine(int)Print("abc");// ends up calling WriteLine(string)

Dynamic lookup is performed using three distinct mechanisms: COM IDispatch for COM objects, IDynamicMetaObjectProvider DLR interface for objects implementing that interface, and reflection for all other objects. Any C# class can therefore intercept dynamic calls on its instances by implementing IDynamicMetaObjectProvider.

In case of dynamic method and indexer calls, overload resolution happens at run-time according to the actual types of the values passed as arguments, but otherwise according to the usual C# overloading resolution rules. Furthermore, in cases where the receiver in a dynamic call is not itself dynamic, run-time overload resolution will only consider the methods that are exposed on the declared compile-time type of the receiver. For example:

classBase{voidFoo(doublex);}classDerived:Base{voidFoo(intx);}dynamicx=123;Baseb=newDerived();b.Foo(x);// picks Base.Foo(double) because b is of type Base, and Derived.Foo(int) is not exposeddynamicb1=b;b1.Foo(x);// picks Derived.Foo(int)

Any value returned from a dynamic member access is itself of type dynamic. Values of type dynamic are implicitly convertible both from and to any other type. In the code sample above this permits GetLength function to treat the value returned by a call to Length as an integer without any explicit cast. At run time the actual value will be converted to the requested type.

Covariant and contravariant generic type parameters

Generic interfaces and delegates can have their type parameters marked as covariant or contravariant using keywords out and in respectively. These declarations are then respected for type conversions, both implicit and explicit, and both compile time and run time. For example, the existing interface IEnumerable<T> has been redefined as follows:

interfaceIEnumerable<outT>{IEnumerator<T>GetEnumerator();}

Therefore, any class that implements IEnumerable<Derived> for some class Derived is also considered to be compatible with IEnumerable<Base> for all classes and interfaces Base that Derived extends, directly or indirectly. In practice, it makes it possible to write code such as:

voidPrintAll(IEnumerable<object>objects){foreach(objectoinobjects){System.Console.WriteLine(o);}}IEnumerable<string>strings=newList<string>();PrintAll(strings);// IEnumerable<string> is implicitly converted to IEnumerable<object>

For contravariance, the existing interface IComparer<T> has been redefined as follows:

publicinterfaceIComparer<inT>{intCompare(Tx,Ty);}

Therefore, any class that implements IComparer<Base> for some class Base is also considered to be compatible with IComparer<Derived> for all classes and interfaces Derived that are extended from Base. It makes it possible to write code such as:

IComparer<object>objectComparer=GetComparer();IComparer<string>stringComparer=objectComparer;

Optional ref keyword when using COM

The ref keyword for callers of methods is now optional when calling into methods supplied by COM interfaces. Given a COM method with the signature

voidIncrement(refintx);

the invocation can now be written as either

Increment(0);// no need for "ref" or a place holder variable any more

or

intx=0;Increment(refx);

Optional parameters and named arguments

C# 4.0 introduces optional parameters with default values as seen in Visual Basic and C++. For example:

voidIncrement(refintx,intdx=1){x+=dx;}intx=0;Increment(refx);// dx takes the default value of 1, after the method returns x == 1Increment(refx,2);// dx takes the value 2, after the method returns x == 3

In addition, to complement optional parameters, it is possible explicitly to specify parameter names in method calls, allowing the programmer selectively to pass any subset of optional parameters for a method. The only restriction is that named parameters must be placed after the unnamed parameters. Parameter names can be specified for both optional and required parameters, and can be used to improve readability or arbitrarily to reorder arguments in a call. For example:

StreamOpenFile(stringname,FileModemode=FileMode.Open,FileAccessaccess=FileAccess.Read){...}OpenFile("file.txt");// use default values for both "mode" and "access" OpenFile("file.txt",mode:FileMode.Create);// use default value for "access"OpenFile("file.txt",access:FileAccess.Read);// use default value for "mode"OpenFile(name:"file.txt",access:FileAccess.Read,mode:FileMode.Create);// name all parameters for extra readability, // and use order different from method declaration

Optional parameters make interoperating with COM easier. Previously, C# had to pass in every parameter in the method of the COM component, even those that are optional. For example:

objectfileName="Test.docx";objectmissing=System.Reflection.Missing.Value;doc.SaveAs(reffileName,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing);

With support for optional parameters, the code can be shortened as

doc.SaveAs(reffileName);

Which, due to the now optional ref keyword when using COM, can further be shortened as

doc.SaveAs(fileName);

Indexed properties

Indexed properties (and default properties) of COM objects are now recognized, but C# objects still do not support them.

Related Research Articles

Generic programming is a style of computer programming in which algorithms are written in terms of 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 duplication. Such software entities are known as generics in Ada, C#, Delphi, Eiffel, F#, Java, Nim, Python, Go, Rust, Swift, TypeScript and Visual Basic .NET. They are known as parametric polymorphism in ML, Scala, Julia, and Haskell ; templates in C++ and D; and parameterized types in the influential 1994 book Design Patterns.

In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.

<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 science, a type signature or type annotation defines the inputs and outputs for a function, subroutine or method. A type signature includes the number, types, and order of the arguments contained by a function. A type signature is typically used during overload resolution for choosing the correct definition of a function to be called among many overloaded forms.

In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.

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.

In computing, type introspection is the ability of a program to examine the type or properties of an object at runtime. Some programming languages possess this capability.

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. Function objects are often called functors.

In compiler construction, name mangling is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages.

{{Short description|Set of rules defining correctijhf ly structured ]. The only exception is the primitive types, which are not represented by ayggv cgo o class instance for performance reasons. Some features like operator overloading or unsigned integer types are omitted to simplify the language and to avoid possible programming mistakes.

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

this, self, and Me are keywords used in some computer programming languages to refer to the object, class, or other entity of which the currently running code is a part. The entity referred to by these keywords thus depends on the execution context. Different programming languages use these keywords in slightly different ways. In languages where a keyword like "this" is mandatory, the keyword is the only way to access data and methods stored in the current object. Where optional, they can disambiguate variables and functions with the same name.

In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.

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

Vala is an object-oriented programming language with a self-hosting compiler that generates C code and uses the GObject system.

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

In computer programming, a constant is a value that should not be altered by the program during normal execution, i.e., the value is constant. When associated with an identifier, a constant is said to be "named," although the terms "constant" and "named constant" are often used interchangeably. This is contrasted with a variable, which is an identifier with a value that can be changed during normal execution, i.e., the value is variable.

The computer programming language, C#, introduces several new features in version 2.0. These include:

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.

Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTSTEP operating system. Due to Apple macOS’s direct lineage from NeXTSTEP, Objective-C was the standard programming language used, supported, and promoted by Apple for developing macOS and iOS applications until the introduction of the Swift programming language in 2014.

References

  1. "Microsoft Visual Studio 2010 First Look". Microsoft .
  2. Torgersen, Mads (2008-10-27). "New features in C# 4.0". Microsoft . Retrieved 2008-10-28.