C Sharp 3.0

Last updated

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. [1] It is not currently standardized by any standards organisation.

Contents

C# 3.0 features

LINQ (language-integrated query)

LINQ is a new Microsoft-specific extensible, general-purpose query language for many kinds of data sources—including plain object collections, XML documents, databases, etc.—which is tightly integrated with other C# language facilities. The syntax is different from, but borrows from SQL. An example:

int[]array={1,5,2,10,7};// Select squares of all odd numbers in the array sorted in descending orderIEnumerable<int>query=fromxinarraywherex%2==1orderbyxdescendingselectx*x;// Result: 49, 25, 1

To implement LINQ, a large range of new methods were added to many collections via the System.Linq.Enumerable class. LINQ expressions are translated to use these functions before compilation. As an alternative, which is sometimes more powerful or direct, these functions may be accessed directly. [2] Doing so makes more use of lambda functions, which are discussed below. The following is functionally identical to the example above.

IEnumerable<int>query=array.Where(x=>x%2==1).OrderByDescending(x=>x).Select(x=>x*x);// Result: 49, 25, 1 using 'array' as defined in previous example

Object initializers

Customerc=newCustomer();c.Name="John";

can be written

Customerc=newCustomer{Name="John"};

Collection initializers

MyListlist=newMyList();list.Add(1);list.Add(2);

can be written as

MyListlist=newMyList{1,2};

assuming that MyList implements System.Collections.IEnumerable and has a public Add method. [3]

Local variable type inference

Local variable type inference:

varx=newDictionary<string,List<float>>();

is interchangeable with

Dictionary<string,List<float>>x=newDictionary<string,List<float>>();

This feature is not just a convenient syntactic sugar for shorter local variable declarations, but it is also required for the declaration of variables of anonymous types. The contextual keyword "var", however, may only appear within a local variable declaration.

Anonymous types

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler.

varx=new{FirstName="John",LastName="Doe"};

Anonymous types are reference types that derive directly from object. The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.

If two or more anonymous types have the same number and type of properties in the same order, the compiler treats them as the same type and they share the same compiler-generated type information. [4]

Lambda expressions

Lambda expressions provide a concise way to write first-class anonymous function values. Compare the following C# 2.0 snippet:

listOfFoo.Where(delegate(Foox){returnx.Size>10;});

with this C# 3.0 equivalent:

listOfFoo.Where(x=>x.Size>10);

In the above examples, lambda expressions are merely shorthand syntax for anonymous delegates with type inference for parameters and return type. However, depending on the context they are used in, a C# compiler can also transform lambdas into ASTs that can then be processed at run-time. In the example above, if listOfFoo is not a plain in-memory collection, but a wrapper around a database table, it could use this technique to translate the body of the lambda into the equivalent SQL expression for optimized execution. Either way, the lambda expression itself looks exactly the same in the code, so the way it is used at run-time is transparent to the client.

Expression trees

Expressions, such as x <= y, a = b + c, or even lambda functions and other complex forms can be created dynamically using expression trees. Much of the functionality is provided by static methods of the class System.Linq.Expressions.Expression. There are also various new classes in that namespace that represent the expressions and partial expressions created by those methods as software objects. These include BinaryExpression, which could represent x <= y; LambdaExpression and many others. When combined with aspects of the reflection API, this can be a very powerful tool, if a little challenging to write and debug. [5] [6]

Automatic properties

The compiler generates a private instance variable and the appropriate accessor and mutator given code such as:

publicstringName{get;privateset;}

Extension methods

Developers may use extension methods to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. In reality, extension methods are a form of syntactic sugar that provide the illusion of adding new methods to the existing class outside its definition. The illusion is achieved with the definition of a static method that is callable as if it were an instance method, where the receiver of the call (i.e., the instance) is bound to the first parameter of the method, decorated with keyword this.

The requirements for an extension method are as follows:

  1. An extension method must be defined in a static class.
  2. An extension method must be defined as a static method.
  3. An extension method's first parameter must take the following form, where type is the name of the type to be extended: this typeparameterName
  4. An extension method may optionally define other parameters to follow the this parameter.

This example class demonstrates the definition and use of a Left extension method for strings:

publicstaticclassStringExtensions{publicstaticstringLeft(thisstrings,intn){returns.Substring(0,n);}}strings="foo bar";s.Left(3);// same as StringExtensions.Left(s, 3), which returns "foo";

Partial methods

Partial methods allow code generators to generate method declarations as extension points that are only included in the compilation if someone actually implements them in another portion of a partial class. [7]

Related Research Articles

In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

F Sharp (programming language) Microsoft programming language

F# is a functional-first, general purpose, strongly typed, multi-paradigm programming language that encompasses functional, imperative, and object-oriented programming methods. F# is most often used as a cross-platform Common Language Infrastructure (CLI) language on .NET, but it can also generate JavaScript and graphics processing unit (GPU) code.

In some programming languages, eval, short for the English evaluate, is a function which evaluates a string as though it were an expression in the language, and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval. The input to eval is not necessarily a string; it may be structured representation of code, such as an abstract syntax tree, or of special type such as code. The analog for a statement is exec, which executes a string as if it were a statement; in some languages, such as Python, both are present, while in other languages only one of either eval or exec is.

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.

Java syntax

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

C Sharp (programming language) Multi-paradigm (object-oriented) programming language

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

Scala (programming language) General-purpose programming language

Scala is a strong statically typed general-purpose programming language which supports both object-oriented programming and functional programming. Designed to be concise, many of Scala's design decisions are aimed to address criticisms of Java.

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.

Oxygene (programming language)

Oxygene is a programming language developed by RemObjects Software for Microsoft's Common Language Infrastructure, the Java Platform and Cocoa. Oxygene is based on Delphi's Object Pascal, but also has influences from C#, Eiffel, Java, F# and other languages.

Haxe is an open source high-level cross-platform programming language and compiler that can produce applications and source code, for many different computing platforms from one code-base. It is free and open-source software, released under the MIT License. The compiler, written in OCaml, is released under the GNU General Public License (GPL) version 2.

C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

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 PHP syntax and semantics are the format (syntax) and the related meanings (semantics) of the text and symbols in the PHP programming language. They form a set of rules that define how a PHP program can be written and interpreted.

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

Nemerle is a general-purpose, high-level, statically typed programming language designed for platforms using the Common Language Infrastructure (.NET/Mono). It offers functional, object-oriented and imperative features. It has a simple C#-like syntax and a powerful metaprogramming system. In June 2012, the core developers of Nemerle were hired by the Czech software development company JetBrains. The team is focusing on developing Nitra, a framework to implement extant and new programming languages. This framework will likely be used to create future versions of Nemerle.

Objective-C is a 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. Objective-C was the standard programming language supported by Apple for developing macOS and iOS applications using their respective application programming interfaces (APIs), Cocoa and Cocoa Touch, until the introduction of Swift in 2014.

References

  1. Anderson, Tim (2006-11-14). "C# pulling ahead of Java - Lead architect paints rosy C# picture". Reg Developer. The Register. Retrieved 2007-01-20.
  2. Walther, Stephen (2008). ASP.NET 3.5 Unleashed . Indiana, USA: SAMS. pp.  916–917. ISBN   978-0-672-33011-7. I find that I use method syntax more than query syntax because query syntax is a subset of method syntax.
  3. Torgersen, Mads (2006-10-10). "What is a collection?". The Mellow Musings of Dr. T. Retrieved 2009-06-18.
  4. "Anonymous Types". C# Programming Guide. Microsoft. July 2008. Retrieved 2009-06-18.
  5. Walther, Stephen (2008). ASP.NET 3.5 Unleashed . Indiana, USA: SAMS. pp.  950–952. ISBN   978-0-672-33011-7.
  6. "Expression Trees". .NET Framework Developer's Guide. Microsoft . Retrieved 2009-04-26.
  7. "Partial Classes and Methods". C# Programming Guide. Microsoft . Retrieved 2009-04-28.