Mid From PDF Power Questions High-Impact Interview Questions

Thread-Safe Singleton?

Incorrect (not thread-safe)

public class Singleton
{
private static Singleton _instance;
}

Correct using double-check locking

public sealed class Singleton
{
private static Singleton _instance;
private static readonly object _lock = new object();
private Singleton() {}
public static Singleton Instance
{

get

{
if (_instance == null)
{

lock(_lock)

{
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
}

Best and simplest

public sealed class Singleton
{
public static readonly Singleton Instance = new Singleton();
private Singleton(){}
}

More from Career Preparation

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details