Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the following code a rock solid way of creating objects from a singleton?

Tags:

c#

I've stumbled accross this code in production and I think It may be causing us problems.

internal static readonly MyObject Instance = new MyObject();

Calling the Instance field twice returns two objects with the same hash code. Is it possible that these objects are different?

My knowledge of the CLI says that they are the same because the hash codes are the same.

Can anyone clarify please?

like image 593
Razor Avatar asked Jun 23 '10 08:06

Razor


2 Answers

The field will only be initialized once, so you'll always get the same object. It's perfectly safe.

Of course, you have to be careful when using static objects from multiple threads. If the object is not thread-safe, you should lock it before accessing it from different threads.

like image 96
Philippe Leybaert Avatar answered Nov 15 '22 09:11

Philippe Leybaert


Yes it is safe - the simplest safe singleton implementation.

As a further point on comparing the hash-code to infer "they're the same object"; since we're talking about reference-types here (singleton being meaningless for value-types), the best way to check if two references point to the same object is:

bool isSame = ReferenceEqual(first, second);

which isn't dependent on the GetHashCode()/Equals/== implementations (it looks at the reference itself).

like image 35
Marc Gravell Avatar answered Nov 15 '22 08:11

Marc Gravell