📜 ⬆️ ⬇️

.NET 4.0: What's new in base classes (BCL)? Detailed review


Visual Studio 2010 and the .NET Framework 4 Beta 2 are already available for download . .NET 4 Beta 2 contains a number of new features and improvements in the base classes (BCL) in addition to those we introduced earlier in .NET 4 Beta 1 . Many of these improvements have been made thanks to customer feedback and recommendations received through Microsoft Connect .

From the translator : this article describes the changes in the base classes that were made from version Beta 1 to Beta 2. At the end of the article I gave a link and a short list of what was added to the base classes of .NET 4.0 earlier.

General list of improvements in .NET 4 Beta 2

Complex type


approx. Transl .: This type can be used by connecting the System.Numerics.dll assembly itself. In addition, some more information can be found in this article.

The System.Numerics.Complex type is a complex number that includes the values ​​of a real number and an imaginary number. Complex supports both Cartesian coordinates (real and imaginary) and polar coordinates (magnitude and period are measured in radians) and supports arithmetic and trigonometric operations. Complex numbers are used in a number of areas, including high-performance computing, plotting graphs and diagrams, electronics (the so-called Fourier transform) and in other areas.

Location


System.Device.Location (which is located in System.Device.dll) allows .NET applications running on Windows 7 to determine the current geolocation (i.e., latitude and longitude) of the device on which the application is running. Windows 7 supports a variety of location sensors, including GPS and WWAN (WWAN radios) devices, and can automatically switch between sensors, when available, to get the most accurate data in a particular situation. .NET applications can use these APIs to access the following data: longitude, latitude, altitude, horizontal and vertical accuracy, direction, speed, and city address (i.e., country / region, state / province, city, zip code, street, house number, floor). Consider that we plan to make some changes to the location-API structure in the next release of .NET RC , so keep this in mind when you are ready to evaluate and use the location-API beta 2 in your applications. We will tell you more about the planned changes in the following articles in this blog.

IObservable <T>


System.IObservable <T> and System.IObserver <T> implement the basic mechanism for push notifications and can be used to create push collections or, in other words, observable collections. Anyone familiar with the patterns will recognize in these interfaces the implementation of a well-known pattern observer . IObservable <T> opens the door to new great paradigms of .NET development for event-based and asynchronous programming. A great example of this is Reactive Framework (RX), a library of extension methods (not included in .NET 4) that implements LINQ Standard Query Operators and other useful stream transformation functions for IObservable <T>. First class events (first-class) F # [app. Translation: more about first-class events and how they differ from .net events can be read in this article ] also support IObservable <T> and, in addition, F # contains a library of operators for browsers similar to RX. Imagine being able to create LINQ requests for events; this is exactly what IObservable <T> allows you to do. To consolidate knowledge of the power of IObservable <T>, I recommend watching the Erik Meijer introducing RX video series by Erik Meijer (Erik Meijer introducing RX ) on Channel 9 and discussing IObservable <T> in the BCL discussing between Wes Dyer and Kim Hamilton (Kim Hamilton)
')
You might think that IObservable <T> comes to replace events in .NET. However, the answer is no, but you really can use IObservable <T> instead of events if you want. Events are a well-known notification mechanism in .NET and are well-known to .NET developers. Therefore, we recommend that you continue to use events as the main notification mechanism for the .NET API. One of the coolest things in IObservable <T> is that converting an existing event to IObservable <T> is the simplest process. RX provides built-in methods for this, and F # contains built-in support at the language level. Stay with our blog for more RX news in the future.

Stream.CopyTo


How often did you write the following stereotype code while working with the Stream type to read from one stream and write to another?

Stream source = ...;
Stream destination = ...;
byte [] buffer = new byte [4096];
int read;
while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
{
destination.Write(buffer, 0, read);
}


* This source code was highlighted with Source Code Highlighter .

In .NET 4, you no longer have to write such code. We have added a new method CopyTo for Stream, which will allow to write like this:

Stream source = ...;
Stream destination = ...;
source.CopyTo(destination);


* This source code was highlighted with Source Code Highlighter .

Guid.TryParse, Version.TryParse, and Enum.TryParse <T>


We added the TryParse method to System.Guid, System.Version, and System.Enum. Enum.TryParse is a generic (generalization), a pleasant improvement over the non-generic Parse method, which allows you to write cleaner code.

In previous versions of .NET, to parse an enumeration value, we could write something like this:
try {
string value = Console .ReadLine();
FileOptions fo = (FileOptions)Enum.Parse( typeof (FileOptions), value );
// Success
}
catch {
// Error
}


* This source code was highlighted with Source Code Highlighter .

In .NET 4 you can use the generic TryParse method:
string value = Console .ReadLine();
FileOptions fo;
if (Enum.TryParse( value , out fo))
{
// Success
}


* This source code was highlighted with Source Code Highlighter .

Note trans .: here could be Enum .TryParse <FileOptions> (value, out fo), but C # is an excellent language whose compiler itself understands everything

Enum.HasFlag


We have added new user-friendly methods in System.Enum, which makes it super-easy to determine if the flag in the Flags enum is set without need to recall bit operators. It also helps to make the code more readable.

In VB:
Dim cm As ConsoleModifiers = ConsoleModifiers.Alt Or ConsoleModifiers.Shift
Dim hasAlt1 As Boolean = (cm And ConsoleModifiers.Alt) = ConsoleModifiers.Alt ' using bitwise operators
Dim hasAlt2 As Boolean = cm.HasFlag(ConsoleModifiers.Alt) ' using HasFlag


* This source code was highlighted with Source Code Highlighter .

In C #:
ConsoleModifiers cm = ConsoleModifiers.Alt | ConsoleModifiers.Shift;
bool hasAlt1 = (cm & ConsoleModifiers.Alt) == ConsoleModifiers.Alt; // using bitwise operators
bool hasAlt2 = cm.HasFlag(ConsoleModifiers.Alt); // using HasFlag


* This source code was highlighted with Source Code Highlighter .

Overloaded String.Concat and String.Join accept IEnumerable <T>


We have added new overloaded versions of String.Concat and String.Join, which accept IEnumerable in addition to the existing overloaded methods that accept arrays. This means that you can pass any collection that implements IEnumerable <T> to these APIs without unnecessary conversion of the collection to an array. We also added params support to the existing array-based String.Join overloaded method, which now allows you to write shorter code.

String .Join( ", " , new string [] { "A" , "B" , "C" , "D" }); // you used to have to write this
String .Join( ", " , "A" , "B" , "C" , "D" ); // now you can write this


* This source code was highlighted with Source Code Highlighter .

String.IsNullOrWhiteSpace


This new convenience method is similar to the existing IsNullOrEmpty method, but in addition to checking a string for null or a null value, it also checks the string for whether it contains only spaces (more precisely, the character defined in Char.IsWhiteSpace). This method can be useful when working with code contracts.

Add-ons in Environment.SpecialFolder


We have added some new values ​​to the Environment.SpecialFolder enumeration:In addition, we added a new, overloaded variant of the Environment.GetFolderPath method that accepts the SpecialFolderOption enumeration, which allows you to specify some additional options, such as “Create” (to create a directory if it does not exist) and “DoNotVerify” (to quickly return the path without checking existence, which is useful when the directory is a shared resource on the network).

Environment.Is64BitProcess and Environment.Is64BitOperatingSystem


These new, useful APIs make it easy to determine the bitness of the current process and operating system. Environment.Is64BitProcess is the equivalent of calling IntPtr.Size == 8. Environment.Is64BitOperatingSystem will inform you that the current operating system is 64-bit. Keep in mind that Environment.Is64BitProcess can return false, and Environment.Is64BitOperatingSystem can be true in a 32-bit process running on a 64-bit system under WOW64 .

Path.Combine parameter support


Have you ever made nested calls to Path.Combine like these:
Path.Combine( "dir1" , Path.Combine( "dir2" , Path.Combine( "dir3" , "dir4" )));

* This source code was highlighted with Source Code Highlighter .

With .NET 4.0, you can write it easier:
Path.Combine( "dir1" , "dir2" , "dir3" , "dir4" );

* This source code was highlighted with Source Code Highlighter .

Globalization while parsing and formatting TimeSpan


In previous versions of .NET, the TimeSpan type was supported only for a single culture-independent format when formatting and parsing. This meant that when you called ToString on a French machine, the output did not match the cultural settings, which made the application non-globalized. Most often, this problem occurred when displaying results from SQL databases that were represented in the widely used type of the Time column. This is because the Time from SQL is mapped to the TimeSpan type in .NET. For example:
Thread.CurrentThread.CurrentCulture = new CultureInfo( "fr-FR" );
Console .WriteLine( new TimeSpan (0, 1, 1, 1, 1));
Console .WriteLine(12.34);


* This source code was highlighted with Source Code Highlighter .

Output:
01:01:01.0010000
12,34

The output from TimeSpan.ToString is in a culture-independent format, so the output is '.' (dot) as separator for decimal types, whereas Double uses ',' (comma) based on current culture settings.

In .NET 4 System.TimeSpan now supports formatting and parsing based on culture settings through the new overloaded methods ToString, Parse and TryParse, as well as the new methods ParseExact and TryParseExact. The default behavior of ToString will remain the previous one and for backward compatibility will display the results in the old form. New loaded methods will allow you to specify the format depending on the culture. You can pass the “g” format (general format) so that the new, overloaded version of ToString uses the culture-sensitive format:

Thread.CurrentThread.CurrentCulture = new CultureInfo( "fr-FR" );
Console .WriteLine( new TimeSpan (0, 1, 1, 1, 1).ToString( "g" ));
Console .WriteLine(12.34);


* This source code was highlighted with Source Code Highlighter .

Output:
01:01:01,0010000
12,34

With this new format, the output of the TimeSpan results coincides with the custom cultural settings.

Stopwatch.Restart


This is a new, useful method - the equivalent of calling Stopwatch.Reset followed by Stopwatch.Start.

StringBuilder.Clear


In previous versions of .NET, you could clear the StringBuilder by setting the Length property to zero. This is not completely obvious, so we added StringBuilder.Clear as a more obvious option.

IntPtr and UIntPtr and Addition and Subtraction Operators


Adding offsets for IntPtr or UIntPtr could lead to errors and, if not performed correctly, was often the source of sophisticated bugs on 64-bit machines. .NET 4 includes add and reduce operations for these types with the Add and Subtract methods, to prevent this type of error.

ServiceProcessInstaller.DelayedAutoStart


Services based on .NET that start automatically can now set the new DelayedAutoStart property to true (recommended), which allows you to delay the start of the service while other services load, plus set a short pause to improve system boot performance when running on Vista and above.

ObservableCollection <T> type moved to System.dll


We moved the types System.Collections.ObjectModel.ObservableCollection <T>, System.Collections.ObjectModel.ReadOnlyObservableCollection <T> and System.Collections.Specialized.INotifyCollectionChanged from WindowsBase.dll (WPF-assembly) in System.dll. This will allow you to use these types without depending on WPF assemblies and will improve the separation between the model and the view.

We hope you enjoy the innovations we made in BCL in .NET 4 Beta 2. Download Visual Studio 2010 and .NET 4 Beta 2 today. Let us know what you think about these things and report bugs .

From the translator:

It was a translation of an article about innovations in .NET 4.0 Beta 2 compared to Beta 1. To get acquainted with new things that were added to .NET 4 even during versions of Beta 1 and CTP, refer to this article . Here I will provide only a general list of innovations:
Progg it

Source: https://habr.com/ru/post/73359/


All Articles