Saturday, January 15, 2011

a good blog about generic and constrain it with "where"


James M. Hare's blog about constraining generics with "where" clause


The blog is thorough. Store it for future reference.

To summarize some key syntaxs as below:

- constrains to an interface or a base class

public class MyClass<T> where T : IMyInterface<T>

- constrains to reference type

where T : class

- Constrain to value type

where T : struct

- Constrain to required consturctor

Where T: class, new()

"Basically, the where clause allows you to specify additional constraints on what the actual type used to fill the generic type placeholder must support." In another word, "if the type meets the given constraint, you can perform the activities that pertain to that constraint with the generic placeholders."

This empowers you to write less code across types. Less is more.

Saturday, January 8, 2011

.Net 4.0 Framework and Lazy<T> - when lazier gets better

Found a couple good blogs abouot Lazy<T> in the new .Net 4.0 framework.

http://sankarsan.wordpress.com/2009/10/04/laziness-in-c-4-0-lazyt/

http://weblogs.asp.net/gunnarpeipman/archive/2009/05/19/net-framework-4-0-using-system-lazy-lt-t-gt.aspx

The key points are:

- When you create a new object, you no longer do "MyClass = new MyClass();". Instead, you do "Lazy<MyClass> = new Lazy<MyClass>();".

- For classes with no parameterless constructor, you need to do below
new Lazy<Pet>(delegate() { return new Pet("DuDu", "Siberian Husky"); });

- The Lazy<T> will NOT instantiate the instance until its value is accessed.

- Its default mode is NOT thread safe.
However, you can make it threadsafe by doing below constructors:

    1) public Lazy(LazyExecutionMode mode)
    2) public Lazy(Func<T> valueFactory,LazyExecutionMode mode)

What is the big gain here? Well, you no longer need to write your own code to implement the laziness as you did in .Net 3.5, or earlier. Instead, the constructor helps you to implement the lazy loading.

Is it cool to be lazier but get the same thing done.