Implicit variables are useful for improve writing and reading code (not in all cases) and they are key for LINQ query expressions:
Before:
Dictionary<string, string> dict = new Dictionary<string, string>(); int[] Numbers = new int[] { 1, 2, 3, 4, 5 }; string[] s = new string[] { "a", "b", "c", "d" };
Now:
var dict = new Dictionary<string, string>(); var Numbers = new[] { 1, 2, 3, 4, 5 }; var s = new[] { "a", "b", "c", "d" };
Extensions Methods
That's an amazing feature for extend interfaces and classes that we don't have the source code or we don't want to modify directly.
Example: Suppose you have an interface that has two properties: Name and Age. Also, it has a method that display its data as 'Name=NameValue Age=AgeValue':
public interface ITestClass { string Name { get; set; } int Age { get; set; } void Show(); }
But, we need to show this data in a different way in several parts of our code, for example: 'NameValue (AgeValue)'. By extending this interface we can simply invoke the method as 'tc.ShowCustom();' like if ShowCustom is part of this interface:
public static class TestClassExtension { public static void ShowCustom(this ITestClass tc) { MessageBox.Show(tc.Name + " (" + tc.Age.ToString() + ")"); } } ... ITestClass tc = GetTestClassInteface(); tc.Name = "Oscar"; tc.Age = 36; tc.Show(); tc.ShowCustom(); // Now it appears like if this method is part of ITestClass (!!! amazing !!!)
NOTE: You can extend standard and base classes/interfaces like String, IEnumerator, etc.
Lambda Expressions
They are key for LINQ expressions and for reduce the use of delegates, here a little example:
var list = new List<string>(); list.Add("one"); list.Add("two"); list.Add("three"); bool bExist = list.Exists(delegate(string s) { return s == "two"; });
And using Lambda Expressions:
bool bExist = list.Exists(s => s == "two");
Anonymous types
Allows the on-the-fly creation of structures:
var person = new { Name = "Oscar", Age = 36 }; MessageBox.Show(person.Name + "(" + person.Age + ")");
Object/Collection Initializers
We can now initialize any property when we are creating some instance for objects or collections:
Timer t = new Timer() { Interval = 30000, Enabled = true }; var list = new List<string> { "one", "two", "three" };
References:
C# 3.0 Tutorial By Jonathan Worthington
C# Version 3.0 Specification MSDN
0 comments:
Post a Comment