I need to share an instance of an object between two static objects as described beneath. The first time I call the property MyProperty I must instantiate MyObject.
As a clever reader, you’ve found the bug. The first time I’ll use the First, I’ll instantiate MyProperty and the first time I’ll use Second, I’ll instantiate MyProperty. That’s reinitialise it and loose all the state of this object.
public static class First
{
static First() { MyProperty = new MyObject(); }
public static MyProperty{ get; set; }
}
public static class Second
{
static Second() { MyProperty = new MyObject(); }
public static MyProperty
{
get { return First.MyProperty; }
set { First.MyProperty= value; }
}
}
The solution in this case is just to check nullity:
static Second()
{
if(MyProperty == null) MyProperty = new MyObject();
}
But, for me there’s a smell. I’ve got the feeling of bad code. So there’s my question: is there a pattern or some good advices to share a context between two static objects?
You do not need the
Secondconstructor, sinceFirst.MyPropertyis initialized byFirstas soon as you access it, no matter whether throughSecondor “directly”. However, as Daniel comments, you might consider using instances. Stateful statics are a smell too.As an alternative, you may consider creation a
Factorywhose constructor takes aMyObject. This factory provides two methods for buildingFirstandSecondinstances, to whichMyObjectis passed. This does require you to pass around the instances instead of accessing the static classes, which I must admit is less convenient.