Saravanan
Saravanan

Reputation: 7854

About the usage of lazy feature in C# 4.0

I have a Userdetails class like the one below

public class UserDetails
{
    public string ssn;

    public string username;

    public string emailid;

    public Address address;
}

Here Address is another class that will have public fields like

public class Address
{
    public int id;

    public string address;
}

Now, when the user logs in the app, i construct the Userdetails object. Now i will not use address object inside the userdetails very frequently, but have got data.

In this scenario how can i use the Lazy initialization feature of C# 4.0.

Note that the data is taken from direct db query and none of these classes have constructors or other means to get the data. These are just representations of the database fields in C#.

Suggest me the best way to use lazy initialization here.

Upvotes: 0

Views: 136

Answers (1)

Petar Ivanov
Petar Ivanov

Reputation: 93030

You can have a private lazy address:

private Lazy<Address> _address = new Lazy<Address>(() => {
    ---code to get the address---
});

public Address address {
    get {
        return _address.Value;
    }    
}

Upvotes: 1

Related Questions