Chris Clark Chris Clark - 2 months ago 14
C# Question

Nullable Bool in Getter Method

The team was discussing at length how we would like to handle a rather large

Account
object.

We don't want to have to initialize every property in the constructor, as this would be too much overhead as that property might never be used on that web page. So we came up with the following.

public partial class Account
{
private bool? projEcho;
public bool ProjectEcho
{
get
{
if (!projEcho.HasValue)
{
projEcho = isProjectEcho();
return (bool)projEcho;
}
else
{
return (bool)projEcho;
}
}
}
}


This way, if someone is using the Account object, and needs to access the property a setter happens internally. We aren't a big fan of this casting technique, but it is the only way to ensure that we have the true/false value when the code has ran. It looks like there is something wrong with this approach, but it seems to be the most efficient way to have a property filled in only when we need it.

My question is: "Is there a better alternative to achieve what we are trying to accomplish from a development standard perspective?"

Answer

There's nothing wrong with the concept - lazy initialization.

You keep a backing field for your property null, and assign a value to it when it is first used. You don't need to cast your nullable bool to a bool, you can use Nullable.Value instead.

private bool? projEcho;
public bool ProjectEcho
    { get
        {
            if (!projEcho.HasValue)
                projEcho = isProjectEcho();
            return projEcho.Value; 
        }
    }

Seems nicer to me. There is also support in .NET for lazy initialization:

https://msdn.microsoft.com/en-us/library/dd997286(v=vs.110).aspx

but i haven't used it much personally.