New features:
VAR
Implicitly Typed Local Variables - compiler will take a best guess at the data type of the expression on the right and make the variable on the left that type.
// i is compiled as an int
var i = 5;
// s is compiled as a string
var s = "Hello";
It is important to understand that the var keyword does not mean “variant” and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.
Anonymous types
Can use VAR to create an object that has one or more public read-only properties.
No defineable type but does have a name to reference it:
var v = new { Amount = 108, Message = "Hello" };Partial Methods/Classes/Structs/Interfaces
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace.
public partial class Employee
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
}
}
//methods
// Definition in file1.cs
partial void onNameChanged();
// Implementation in file2.cs
partial void onNameChanged()
{
// method body
}
Auto-Implemented Properties
class LightweightCustomer
{
public double TotalPurchases { get; set; }
public string Name { get; private set; } // read-only
public int CustomerID { get; private set; } // read-only
}
Object and Collection Initializers¶
private class Cat
{
// Auto-implemented properties
public int Age { get; set; }
public string Name { get; set; }
}
static void MethodA()
{
// Object initializer
Cat cat = new Cat { Age = 10, Name = "Sylvester" };
// Collection initializer
List digits = new List { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List digits2 = new List { 0 + 1, 12 % 3, MakeInt() };
List moreCats = new List
{
new Cat(){ Name="Furrytail", Age=5 },
new Cat(){ Name="Peaches", Age=4},
null
};
}