-
C# 3.0 new features
No CommentsThis post is aimed to be a quick abstract for all the new C# language constructs introduced with the version 3.0.
Implicitly typed local variables
By using var keyword to define a local (does not work at class level) variable is not needed to define its type, the compiler will infer it.
Examples:
var i = 0;
var intArr = new[] { 0, 1, 2, 3 };Object and Collection Initializers
Object’s properties can be initialized when creating the object and also the collection items.
Examples:
TextBox txt = new TextBox() { Text = "John", Width = 200 };
List<string> colorspaces = new List<string> {"RGB", "CMYK", "GreyScale", "B/W"};
Anonymous types
By combining the previous two features (Implicitly typed variables and Object initializers) you can create anonymous types (statically typed, with no name used in the code).
Example:
var guy = new { FirstName = "John", LastName = "Doe" };
Console.WriteLine(guy.FirstName);Automatically Implemented Properties
You can create properties with no need for a private member to store its value.
Examples:
public string Name { get; set; }
//read-only property
public byte Age { get; private set; }Extension methods
By using the this keyword in a static method argument you can extend another class. You "injects" methods to an existing class from another one.
Example:
public static class ExtensionClass
{
//Extension method
public static byte ToGray(this Color c)
{
return (byte)(0.3 * c.R + 0.59 * c.G + 0.11 * c.B);
}
}byte pixelGray = Color.Green.ToGray();
Lambda Expressions
Lambda expressions are like pretty simple functions that takes input parameters and evaluates an expression.
Syntax:
(input parameters) => expression
Examples:
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);Console.WriteLine(oddNumbers.ToString());
Func<int, int> duplicate = number => number * 2;
Console.WriteLine(duplicate.Invoke(2).ToString()); -
Leave a comment
Your email address will not be published.