Friday, August 28, 2015

Things learned from C# in Depth

I recently finished reading through C# in Depth , and I learned a ton about language features that I haven't been using. Many of these features allow for cleaner code and less code, which both make my job easier. 

Automatic property initializer
public string MyString
{ get; set;}
Easier object initialization
new MyClass()
     new Product   {name=value},
     new Product()
Named arguments
public method(int a)
call like Method(a:5)
Lambda expression – these basically remove the nastiness of using delegates
products.Sort(delegate(Product x, Product y)    
                            return x.Name.CompareTo(y.Name); 
                       } );

Using lambda
products.Sort((x, y) => x.Name.CompareTo(y.Name));
Extension methods – you know how you have global utility class? Extensions methods make it look like a method is part of the class calling it, which clarifies intent.
static void DoStuff(this MyClass mc, string me)
{ = me }

In the calling code...
Mc = new MyClass();

Enumerable has a lot of extension methods available.

Nullable types and the null coalescing operator (??) – these features make parsing database results a lot easier.
int? A = null
int B = 5
int C = a ?? b
C would be set to B, because A is null

Optional parameters – so you don’t have to have a whole bunch of overloads
public void DoStuff(int a, int b = 2)

caller can then do DoStuff(1) or DoStuff(1, 3)
Implicitly typed local variables using ‘var’
var m = new MyClassWithAReallyLongName();

LINQ is a huge feature, that really improves the way you handle data processing. To me, it allows you write SQL-like statements in C# for any data source (objects, database, xml).

I knew of this before, but just haven’t used it. One of the huge benefits of LINQ that I can put into practice right away is replacing raw SQL queries with LINQ-to-SQL.
var query = from user in userList           
                    select user;

this gets transformed by the compiler to the following:

var query = userList .Select(user => user);

You can type either statement.

LINQ-to-XML – putting this here separately from LINQ.

Working with XML programmatically has always been awkward, am I right? Well, LINQ-to-XML makes it feel natural. The statements you type pretty much look exactly like the resulting XML doc!
new XElement("root",    
        new XElement("person",      
                new XElement("job", "coder")),   
        new XElement("other-person"));

Would generate this
</ person > 
  <other-person />

dynamic keyword – declare a type without the type being known at compile time. This is excellent for interop. I don’t think I’ll use this often.

To boil it down into one sentence: this removes a lot of the tediousness when writing asynchronous code
Anonymous type

These are good when you don’t want to take the time to create a fullblown class for a simple data container class.
var spot = new { Name = "Spot"}; 
var rex = new { Name = "Rex”};

Anonymous methods

When a method wants a delegate, you can pass it an anonymous method. This is awesome, because then you don’t have to type out the method somewhere else. Programmers just hate typing!
x.ForEach(n => Console.WriteLine(Math.Sqrt(n));

Namespace alias

Useful when you don’t feel like typing out the full namespace, or ya know, when you want to clarify intent.
using WinForms = System.Windows.Forms; 
Monitor.Enter(lock, ref wasAcquired) 

This can be used to do the Enter call in a try-catch, then release the lock in the finally if the lock was acquired. Better than Monitor.Enter(lock).

No comments:

Post a Comment

There was an error in this gadget