4.11. Changes to Existing Functionality

.NET 4.0 enhances a number of existing commonly used methods and classes.

4.11.1. Action and Func Delegates

Action and Func delegates now can accept up to 16 generic parameters, which might result in unreadable code.

4.11.2. Compression Improvements

The 4GB size limit has been removed from System.IO.Compression methods. The compression methods in DeflateStream and GZipStream do not try to compress already compressed data, resulting in better performance and compression ratios.

4.11.3. File IO

.NET 4.0 introduces a new method to the File class called File.ReadLines(), which returns IEnumerable<string> rather than a string array. Reading a file one line at a time is much more efficient than loading the entire contents into memory (File.ReadAllLines()).

This technique also has the advantage that you can start working with a file immediately and bail out of the loop when you find what you are looking for without having to read the entire file. ReadLines() is now the preferred method for working with very large files.

IEnumerable<string> FileContent=File.ReadLines("MyFile.txt");
foreach(string Line in FileContent)
{
    Console.Write(Line);
}

File.WriteAllLines() and File.AppendAllLines() now take an IEnumerable<string> as an input parameter.

System.IO.Directory has the following new static methods that return IEnumerable<string>:

  • EnumerateDirectories(path)

  • EnumerateFiles(path)

  • EnumerateFileSystemEntries(path)

System.IO.DirectoryInfo has the following new static methods:

  • EnumerateDirectories(path) returns IEnumerable<DirectoryInfo>

  • EnumerateFiles(path) returns IEnumerable<FileInfo>

  • EnumerateFileSystemInfos(path) returns IEnumerable<FileSystemInfo>

Enumerating files within a directory is also now more efficient than previously because file metadata such as a creation date is queried during enumeration. This means that Windows API calls should be unnecessary because the information is already retrieved.

4.11.4. Path.Combine()

The Path.Combine() method has new overloads that accept three and four parameters and an array of strings.

4.11.5. Isolated Storage

The default space allocation for isolated storage has now been doubled.

4.11.6. Registry Access Changes

The RegistryKey.CreateSubKey() method has a new option that allows the passing in of a RegistryOptions enumeration, allowing you to create a volatile registry key. Volatile registry keys are not persisted during reboots, so they are great for storing temporary data in. The following code shows how to create a volatile registry key:

var key = instance.CreateSubKey(subkey, RegistryKeyPermissionCheck.Default,
RegistryOptions.Volatile);

In 64-bit versions of Windows, data is stored separately in the registry for 32- and 64-bit applications. The OpenBaseKey() and OpenRemoteBaseKey() methods now allow you to specify a new enum called RegistryView for specifying the mode that should be used when reading. Note that if you mistakenly use the 64-bit option on a 32-bit version, you will get the 32-bit view.

4.11.7. Stream.CopyTo()

Stream.CopyTo() allows you to copy the contents of one stream to another, avoiding some tedious coding:

MemoryStream destinationStream = new MemoryStream();

using (FileStream sourceStream = File.Open(@"c:	emp.txt", FileMode.Open))
{
    sourceStream.CopyTo(destinationStream);
}

4.11.8. Guid.TryParse(), Version.TryParse(), and Enum.TryParse<T>()

New TryParse() methods have been added to Guid, Version, and Enum types:

Guid myGuid;
Guid.TryParse("not a guid", out myGuid);

4.11.9. Enum.HasFlag()

The Enum.HasFlag() method returns a Boolean value indicating whether one or more flags are set on an enum. For example, you could use the HasFlag() method to test whether a car has particular options set:

[Flags]
public enum CarOptions
{

    AirCon = 1,
    Turbo = 2,
    MP3Player = 4
}

static void Main(string[] args)
{
    CarOptions myCar = CarOptions.MP3Player | CarOptions.AirCon | CarOptions.Turbo;
    Console.WriteLine("Does car have MP3? {0}", myCar.HasFlag(CarOptions.MP3Player));
    Console.ReadKey();
}

4.11.10. String.Concat() and String.Join() support IEnumerable<T>

New overloads allow the concatenation and joining of IEnumerable elements without having to convert them to strings first, which can make LINQ queries cleaner.

4.11.11. String.IsNullOrWhiteSpace()

String.IsNullOrWhiteSpace() detects if a string is null or empty, or consists of whitespace characters (avoiding a call to Trim()):

String.IsNullOrWhiteSpace(" ");

This is one of my favorite changes. It is such a common thing to do that it is great to have it baked into the framework.

4.11.12. StringBuilder.Clear()

StringBuilder.Clear() removes content from the StringBuilder object (essentially the same as setting a StringBuilder's length to 0, but with a more readable syntax):

StringBuilder sb = new StringBuilder("long string");
sb.Clear();

Note that calling StringBuilder.Clear() does not reset the MaxCapacity property.

4.11.13. Environment.SpecialFolder Enum Additions

The SpecialFolder enum has had a number of new options added to represent pretty much any type of folder on a Windows machine. For example, you can access the CDBuring folder:

Environment.SpecialFolder.CDBurning

4.11.14. Environment.Is64BitProcess and Environment.Is64BitOperatingSystem

64-bit is becoming mainstream now, so new methods have been added to return a Boolean value, indicating whether your application or process is running in a 64-bit process or on a 64-bit system:

Console.WriteLine(Environment.Is64BitOperatingSystem);
Console.WriteLine(Environment.Is64BitProcess);

4.11.15. Stopwatch.Restart()

Stopwatch.Restart() stops the recording of the current time period and starts a new one:

var sw = new Stopwatch();
sw.Start();
sw.Restart();

4.11.16. ServiceProcessInstaller.DelayedAutoStart

.NET services running on Vista or above can make use of the ServiceProcessInstaller. DelayedAutoStart feature to delay their start until other autostart services have already started. This can reduce the boot time for users.

4.11.17. Observable Collection Refactoring

ObservableCollection<T>, ReadOnlyObservableCollection<T>, and System.Collections.Specialized.INotifyCollectionChanged have been moved into System.dll because they were useful outside of WPF applications. This is great news because you no longer have to reference WPF assemblies.

4.11.18. IObservable<T>

IObservable<T> is aninterface for implementation of the observer pattern.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.134.198