Being Lazy in C# 4

10/13/10

Permalink 09:57:25 pm, by truewill Email , 121 words, 234 views   English (US)
Categories: C#, .NET

Being Lazy in C# 4

I’m playing with the new features of C#/.NET 4.0; this is some code I wrote in LINQPad to try out the System.Lazy<T> class.

void Main()
{
    Console.WriteLine("Running...");
    Expensive one = GimmeOne;
    Expensive two = GimmeOne;
    
    if (one == two) Console.WriteLine("Same instance");
}

private static readonly Lazy<Expensive> _lazy =
  new Lazy<Expensive>();
// If constructor arguments, use:
// new Lazy<Expensive>(() => new Expensive(args));

Expensive GimmeOne
{
    get
    {
        return _lazy.Value;  // thread safe
    }
}

class Expensive
{
    public Expensive()
    {
        Console.WriteLine("Creating expensive instance");
    }
}

Output:

Running...
Creating expensive instance
Same instance

Update - October 14, 2010

The private field does not have to be static; there’s seldom a need for a true Singleton.

Comments, Pingbacks:

No Comments/Pingbacks for this post yet...

Leave a comment:

Your email address will not be displayed on this site.
Your URL will be displayed.

Allowed XHTML tags: <p, ul, ol, li, dl, dt, dd, address, blockquote, ins, del, span, bdo, br, em, strong, dfn, code, samp, kdb, var, cite, abbr, acronym, q, sub, sup, tt, i, b, big, small>
(Line breaks become <br />)
(Set cookies for name, email and url)
(Allow users to contact you through a message form (your email will NOT be displayed.))
The name truewill is composed of two other words. What is the SECOND word?

Development Central

Development Central is the blog of Bill Sorensen, a professional software developer. Much of this will relate to C#, .NET, and OOP in general.

Disclaimer
These postings are provided "AS IS" with no warranties and confer no rights.

Search

Categories

Linkblog

b2evolution

contributors

XML Feeds

What is RSS?

Who's Online?

  • Guest Users: 3

powered by b2evolution free blog software