Reputation: 24562
My code looks like this:
public static DataManager _db;
public static DataManager DB
{
get
{
if (_db == null)
{
_db = new DataManager();
}
return _db;
}
}
I have used get => and set => throughout the code but I am not sure how to do it here. Can someone give me advice on this?
Also I have seen people using { get; } when declaring. Is that something that could be applied to the first line below?
Upvotes: 5
Views: 89
Reputation: 117037
Using Lazy<>
is the way to go.
private static Lazy<DataManager> _ldb = new Lazy<DataManager>(() => new DataManager());
public static DataManager DB => _ldb.Value;
It's thread-safe and uses deferred execution.
Upvotes: 0
Reputation: 81493
You can Lazy Load (term used loosely) with an Expression Body Property and a Null-Coalescing Operator (??
)
private static DataManager _db;
public static DataManager DB => _db ?? ( _db = new DataManager());
Be warned, this is not considered thread safe
If you want this thread safe consider using Lazy<T>
with the appropriate constructor
you can also use an auto initalizer
public static Bob DB2 { get; } = new Bob();
Basically this is just a read-only property that (in this case) is set immediately before the class is statically constructed, in short meaning the first time it gets used in anger.
What's the difference you may ask?
In the first part, the property isn't loaded until you actually call it. You may call it a lazy pattern if you will.
In the second part, the property is loaded the first time you access the static class.
Additional Resources
The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
Expression-bodied members (C# programming guide)
Support for expression body definitions was introduced for methods and property get accessors in C# 6 and was expanded in C# 7.0. Expression body definitions can be used with the type members listed in the following table: Member
Supported as of...
- Method C# 6
- Constructor C# 7.0
- Finalizer C# 7.0
- Property Get C# 6
- Property Set C# 7.0
- Indexer C# 7.0
Auto-Implemented Properties (C# Programming Guide)
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
Provides support for lazy initialization.
Upvotes: 7