Is returning a reference from static method thread-safe?

c#, multithreading

Solution

Yes? Without knowing the internals of the constructor of that class, you could say that calling `GetInstance()` was thread safe. Any methods on that instance would not be guaranteed to be thread safe though, particularly since you didnt present any of those methods.

This is simply known as the factory pattern.

EDIT: If you are trying to return a singleton, you can do it like so:

.NET 4+

private static Lazy<PrintStringDataBuilder> _instance = new Lazy<PrintStringDataBuilder>(() =>
  {
      return new PrintStringDataBuilder();
  });

public static PrintStringDataBuilder GetInstance()
{
    return _instance.Value;
}

.NET 3.5 and below

private static PrintStringDataBuilder _instance = null;
private static object _lockObject = new object();

public static PrintStringDataBuilder GetInstance()
{
    if(_instance == null)
    {
         lock(_lockObject)
         {
              if(_instance == null)
                 _instance = new PrintStringDataBuilder();
         }
    }

    return _instance;
}

Problem

I have a class: ``` class PrintStringDataBuilder { PrintStringDataBuilder() { } public static GetInstance() { return new PrintStringDataBuilder(); } //other class methods and fields, properties } ``` Accessed from client Code as: ``` PrintStringDataBuilder instance = PrintStringDataBuilder.GetInstance(); ``` Is above call thread-safe? Edit: Just trying to avoid writing PrintStringDataBuilder builder = new PrintStringDataBuilder(); multiple times in asp.net mvc web app. There are no other static methods, static fields or static properties in the PrintStringDataBuilder class.

Original source