Saturday, December 29, 2012

.NET 3.5 new feature:

.NET 3.5 new feature:
1.
The shortcut of automatic implemented properties:
public int MyProperty { get; set; }

2. Object and Collection Initializers

C# 2008 now allows you to assign values to an object's properties at the moment the property is initialized. For instance, suppose you have the following object in your code:

public class MyStructure
{
       public int MyProperty1 { get; set; }
       public int MyProperty2 { get; set; }
}
Using C# 2008, you can instantiate the MyStructure object as follows:

MyStructure myStructure = new MyStructure() { MyProperty1 = 5,
  MyProperty2 = 10 };
This same capability allows you to declare many items of a collection at once:

List <int> myInts = new List <int> () { 5, 10, 15, 20, 25 };
In this case, all the numbers are added to the myInts object as if you used the Add() method.

3. Using LINQ, you can query against objects, data sets, the SQL Server database, XML, and more. The nice thing is that regardless of the underlying data source, getting at the data is done in the same manner because LINQ provides a structured way to query the data.
4.
a constant is a variable whose value cannot be changed throughout its lifetime. Constants are always implicitly static. However, notice that you don't have to (and, in fact, are not permitted to) include the static modifier in the constant declaration.
5.
To specify that your number is a decimal type rather than a doublefloat, or an integer, you can append the M (or m) character to the value, as shown in the following example:
decimal d = 12.30M;
6.
A C++ char represents an 8-bit character, whereas a C# char contains 16 bits. This is part of the reason that implicit conversions between the char type and the 8-bit byte type are not permitted.
7.You can prefix a string literal with the at character (@) and all the characters in it will be treated at face value; they won't be interpreted as escape sequences:
string filepath = @"C:\ProCSharp\First.cs";
7.
You can also specify a width for the value, and justify the text within that width, using positive values for right-justification and negative values for left-justification. To do this, use the format { n, w }, where n is the parameter index and w is the width value:
int i = 940;
int j = 73;
Console.WriteLine("{0,4}\n+{1,4}\n ---- \n {2,4}", i, j, i + j);
The result of this is:
 940
+  73
----
1013
 Open table as spreadsheet
String
Description
C
Local currency format.
D
Decimal format. Converts an integer to base 10, and pads with leading zeros if a precision specifier is given.
E
Scientific (exponential) format. The precision specifier sets the number of decimal places (6 by default). The case of the format string (e or E) determines the case of the exponen-tial symbol.
F
Fixed-point format; the precision specifier controls the number of decimal places. Zero is acceptable.
G
General format. Uses E or F formatting, depending on which is more compact.
N
Number format. Formats the number with commas as thousands separators, for example 32,767.44.
P
Percent format.
X
Hexadecimal format. The precision specifier can be used to pad with leading zeros.

Note that the format strings are normally case insensitive, except for e / E.
If you want to use a format string, you should place it immediately after the marker that gives the parameter number and field width, and separate it with a colon. For example, to format a decimal value as currency for the computer's locale, with precision to two decimal places, you would use C2:

decimal i = 940.23m;
decimal j = 73.7m;
Console.WriteLine("{0,9:C2}\n+{1,9:C2}\n ---------\n {2,9:C2}", i, j, i + j);
The output of this in U.S. currency is:

  $940.23
+   $73.70
---------
$1,013.93
As a final trick, you can also use placeholder characters instead of these format strings to map out formatting. For example:

double d = 0.234;
Console.WriteLine("{0:#.00}", d);
This displays as.23, because the # symbol is ignored if there is no character in that place, and zeros will either be replaced by the character in that position if there is one or be printed as a zero.
8.
XML Documentation
In addition to the C-type comments, illustrated in the preceding section, C# has a very neat feature that we want to highlight: the ability to produce documentation in XML format automatically from special comments. These comments are single-line comments but begin with three slashes (///) instead of the usual two. Within these comments, you can place XML tags containing documentation of the types and type members in your code.
The tags in the following table are recognized by the compiler. Open table as spreadsheet
Tag
Description
<c>
Marks up text within a line as code, for example <c>int i = 10;</c>.
<code>
Marks multiple lines as code.
<example>
Marks up a code example.
<exception>
Documents an exception class. (Syntax is verified by the compiler.)
<include>
Includes comments from another documentation file. (Syntax is verified by the compiler.)
<list>
Inserts a list into the documentation.
<param>
Marks up a method parameter. (Syntax is verified by the compiler.)
<paramref>
Indicates that a word is a method parameter. (Syntax is verified by the compiler.)
<permission>
Documents access to a member. (Syntax is verified by the compiler.)
<remarks>
Adds a description for a member.
<returns>
Documents the return value for a method.
<see>
Provides a cross-reference to another parameter. (Syntax is verified by the compiler.)
<seealso>
Provides a "see also" section in a description. (Syntax is verified by the compiler.)
<summary>
Provides a short summary of a type or member.
<value>
Describes a property.

To see how this works, add some XML comments to the MathLibrary.cs file from the "More on Compiling C# Files" section, and call it Math.cs. You will add a <summary>element for the class and for its Add() method, and also a <returns> element and two <param> elements for the Add() method:
9.

The C# Preprocessor Directives

#define and #undef

#define isn't much use on its own, but when combined with other preprocessor directives, especially #if, it becomes very powerful.

#if, #elif, #else, and #endif

These directives inform the compiler whether to compile a block of code. Consider this method:
int DoSomeWork(double x)
{
  // do something
  #if DEBUG
     Console.WriteLine("x is " + x);
  #endif
}

#warning and #error

Two other very useful preprocessor directives are #warning and #error. These will respectively cause a warning or an error to be raised when the compiler encounters them. If the compiler sees a #warning directive, it will display whatever text appears after the #warning to the user, after which compilation continues. If it encounters a #errordirective, it will display the subsequent text to the user as if it were a compilation error message and then immediately abandon the compilation, so no IL code will be generated.
You can use these directives as checks that you haven't done anything silly with your #define statements; you can also use the #warning statements to remind yourself to do something:
#if DEBUG && RELEASE
  #error "You've defined DEBUG and RELEASE simultaneously!"
#endif

#warning "Don't forget to remove this line before the boss tests the code!"
  Console.WriteLine("*I hate this job.*");

#region and #endregion

The #region and #endregion directives are used to indicate that a certain block of code is to be treated as a single block with a given name, like this:
#region Member Field Declarations
  int x;
  double d;
  Currency balance;
#endregion
This doesn't look that useful by itself; it doesn't affect the compilation process in any way. However, the real advantage is that these directives are recognized by some editors, including the Visual Studio .NET editor. These editors can use these directives to lay out your code better on the screen. You will see how this works in Chapter 15,"Visual Studio 2008."

#pragma

The #pragma directive can either suppress or restore specific compiler warnings. Unlike command-line options, the #pragma directive can be implemented on a class or method level, allowing a fine-grained control of what warnings are suppressed and when. The following example disables the "field not used" warning and then restores it after the MyClassclass compiles:
#pragma warning disable 169
public class MyClass
{
 int neverUsedField;
}
#pragma warning restore 169
10.
public string ForeName  {get; private set;}
11.
The .NET runtime makes no guarantees about when a static constructor will be executed, so you should not place any code in it that relies on it being executed at a particular time (for example, when an assembly is loaded). Nor is it possible to predict in what order static constructors of different classes will execute. However, what is guaranteed is that the static constructor will run at most once, and that it will be invoked before your code makes any reference to the class. In C#, the static constructor usually seems to be executed immediately before the first call to any member of the class.
Notice that the static constructor does not have any access modifiers. It ' s never called by any other C# code, but always by the .NET runtime when the class is loaded, so any access modifier like public or private would be meaningless. For this same reason, the static constructor can never take any parameters, and there can be only one static constructor for a class. It should also be obvious that a static constructor can access only static members, not instance members, of the class.
However, if any static fields have been given default values, these will be allocated before the static constructor is called.
It would clearly be neater to place all the code in one place, and C# has a special syntax, known as a constructor initializer, to allow this:

class Car
{
  private string description;
  private uint nWheels;

  public Car(string description, uint nWheels)
  {
     this.description = description;
     this.nWheels = nWheels;
  }

  public Car(string description) : this(description, 4)
  {
  }
  // etc
A C# constructor initializer may contain either one call to another constructor in the same class (using the syntax just presented) or one call to a constructor in the immediate base class (using the same syntax, but using the keyword base instead of this). It is not possible to put more than one call in the initializer.
12.
The readonly keyword gives a bit more flexibility than const, allowing for situations in which you might want a field to be constant but also need to carry out some calculations to determine its initial value. The rule is that you can assign values to a readonly field inside a constructor, but not anywhere else. It ' s also possible for a readonly field to be an instance rather than a static field, having a different value for each instance of a class. This means that, unlike a const field, if you want a readonly field to be static, you have to declare it as such.
public class DocumentEditor
  {
     public static readonly uint MaxDocuments;

     static DocumentEditor()
     {
        MaxDocuments = DoSomethingToFindOutMaxNumber();
     }
13.
In many ways, you can think of structs in C# as being like scaled-down classes. They are basically the same as classes but designed more for cases where you simply want to group some data together. They differ from classes in the following ways:
  • Structs are value types, not reference types. This means they are stored either in the stack or inline (if they are part of another object that is stored on the heap) and have the same lifetime restrictions as the simple data types.
  • Structs do not support inheritance.
  • There are some differences in the way constructors work for structs. In particular, the compiler always supplies a default no-parameter constructor, which you are not permitted to replace.
  • With a struct, you can specify how the fields are to be laid out in memory
Because structs are really intended to group data items together, you ' ll sometimes find that most or all of their fields are declared as public. This is, strictly speaking, contrary to the guidelines for writing .NET code — according to Microsoft, fields (other than const fields) should always be private and wrapped by public properties. However, for simple structs, many developers would nevertheless consider public fields to be acceptable programming practice.
Although structs are value types, you can often treat them syntactically in the same way as classes. For example, with the definition of the Dimensions class in the previous section, you could write:

  Dimensions point = new Dimensions();
  point.Length = 3;
  point.Width = 6;
Note that because structs are value types, the new operator does not work in the same way as it does for classes and other reference types. Instead of allocating memory on the heap, the new operator simply calls the appropriate constructor, according to the parameters passed to it, initializing all fields. Indeed, for structs it is perfectly legal to write:
  Dimensions point;
  point.Length = 3;
  point.Width = 6;
That said, the default constructor, which initializes all fields to zero values, is always present implicitly, even if you supply other constructors that take parameters. It ' s also impossible to circumvent the default constructor by supplying initial values for fields. The following code will cause a compile-time error:
  struct Dimensions
  {
     public double Length = 1;       // error. Initial values not allowed
     public double Width = 2;        // error. Initial values not allowed
  }
Structs are always derived from System.ValueType
14.
The partial keyword allows the class, struct, or interface to span across multiple files. Typically, a class will reside entirely in a single file. However, in situations where multiple developers need access to the same class, or more likely in the situation where a code generator of some type is generating part of a class, then having the class in multiple files can be beneficial.
15.
If a class contains nothing but static methods and properties, the class itself can become static. A static class is functionally the same as creating a class with a private static constructor. An instance of the class can never be created. By using thestatic keyword, the compiler can help by checking that instance members are never accidentally added to the class.
16.
Note that this method must be declared as override because it is replacing (overriding) the ToString() method supplied by Object.
     public override string ToString()
     {
        return "$" + Amount.ToString();
     }
17.
Extension methods can help by allowing you to change a class without requiring the source code for the class.
Extension methods are static methods that can appear to be part of a class without actually being in the source code for the class. Let ' s say that the Money class from the previous example needs to have a method AddToAmount(decimal amountToAdd). However, for whatever reason the original source for the assembly cannot be changed directly. All that you have to do is create a static class and add the AddToAmount method as a static method. Here is what the code would look like:

namespace Chapter3.Extensions
{
 public static class MoneyExtension
 {
   public static void AddToAmount(this Money money, decimal amountToAdd)
   {
     money.Amount += amountToAdd;
   }
 }
}
Notice the parameters for the AddToAmount method. For an extension method, the first parameter is the type that is being extended preceded by the this keyword. This is what tells the compiler that this method is part of the Money type. In this example Money is the type that is being extended. In the extension method you have access to all the public methods and properties of the type being extended.
In the main program the AddToAmount method appears just as another method. The first parameter doesn ' t appear, and you do not have to do anything with it. To use the new method, you make the call just like any other method:

cash1.AddToAmount(10M);
18.
Accordingly, C# does not support multiple implementation inheritance. It does, however, allow types to be derived from multiple interfaces — multiple interface inheritance.
By declaring a base class function as virtual, you allow the function to be overridden in any derived classes:
class MyBaseClass
{
  public virtual string VirtualMethod()
  {
     return "This method is virtual and defined in MyBaseClass";
  }
}
It is also permitted to declare a property as virtual. For a virtual or overridden property, the syntax is the same as for a nonvirtual property, with the exception of the keywordvirtual, which is added to the definition. The syntax looks like this:
public virtual string ForeName
{
  get { return fName;}
  set { fName = value;}
19.
C# allows both classes and functions to be declared as abstract. An abstract class cannot be instantiated, whereas an abstract function does not have an implementation, and must be overridden in any non-abstract derived class. Obviously, an abstract function is automatically virtual (although you don't need to supply the virtual keyword; doing so results in a syntax error). If any class contains any abstract functions, that class is also abstract and must be declared as such:
abstract class Building
{
  public abstract decimal CalculateHeatingCost();   // abstract method
}
C# allows classes and methods to be declared as sealed. In the case of a class, this means that you can't inherit from that class. In the case of a method, this means that you can't override that method.
20.
Visibility modifiers indicate which other code items can view an item.
Modifier
Applies To
Description
public
Any types or members
The item is visible to any other code.
protected
Any 
member of a type, also any nested type
The item is visible only to any derived type.
internal
Any member of a type, also any nested type
The item is visible only within its containing assembly.
private
Any types or members
The item is visible only inside the type to which it belongs.
protected internal
Any member of a type, also any nested type
The item is visible to any code within its containing assembly and also to any code inside a derived type.


Other Modifiers
The modifiers in the following table can be applied to members of types and have various uses. A few of these modifiers also make sense when applied to types.
Modifier
Applies To
Description
new
Function members
The member hides an inherited member with the same signature.
static
All members
The member does not operate on a specific instance of the class.
virtual
Classes and function members only
The member can be overridden by a derived class.
abstract
Function members only
A virtual member that defines the signature of the member, but doesn't provide an implementation.
override
Function members only
The member overrides an inherited virtual or abstract member.
sealed
Classes, methods, and properties
For classes, the class cannot be inherited from. For properties and methods, the member overrides an inherited virtual member, but cannot be overridden by any members in any derived classes. Must be used in conjunction with override.
extern
Static[DllImport]methods only
The member is implemented externally, in a different language.

internal acts in much the same way as public, but access is confined to other code in the same assembly — that is, code that is being compiled at the same time in the same program. You can use internal to ensure that all the other classes that you are writing have access to a particular member, while at the same time hiding it from other code written by other organizations

21.
After declaring an array, memory must be allocated to hold all the elements of the array. An array is a reference type, so memory on the heap must be allocated. You do this by initializing the variable of the array using the new operator with the type and the number of elements inside the array. Here you specify the size of the array:
 myArray = new int[4];

22.
Boxing and its counterpart, unboxing, allow you to convert value types to reference types and then back to value types. 

23.
Callback functions are really pointers to a method call. Also known as function pointers, they are a very powerful programming feature. .NET has implemented the concept of a function pointer in the form of delegates. What makes them special is that, unlike the C function pointer, the .NET delegate is type-safe. 

No comments:

Post a Comment