Instatiating an object in the get property method

  • Thread starter Thread starter Jack Addington
  • Start date Start date
J

Jack Addington

Is it bad form to instatiate a private variable in the get method of a
property declaration?

ie)

private objA _someVar;

public objA SomeVar
{
get { if( _someVar == null) _someVar = new objA();
return _someVar;
}
}
 
Jack,

No, this is not a bad idea at all. It's referred to as "lazy-loading"
and is done when the resource is expensive to create.

The only problem with this is that it is not thread safe. If this is
the case, then you will have to use a lock statement (I recommend the double
check lock pattern) to create the instance if it is not created already.

Hope this helps.
 
Hi, Jack.
As long as the design is solid, I don't see any systematic problem with
this technic. For example, it could be used to perform a delayed instantiate
a singleton object.

Ming Chen
 
Nicholas Paldino said:
No, this is not a bad idea at all. It's referred to as "lazy-loading"
and is done when the resource is expensive to create.

The only problem with this is that it is not thread safe. If this is
the case, then you will have to use a lock statement (I recommend the double
check lock pattern) to create the instance if it is not created already.

The double-check lock pattern doesn't work in .NET unless the variable
is also volatile. There's no guarantee that the object will have
completed being constructed before the value in the variable is set to
the new reference, for example.
 
but if you are running the code on a x86 machine, double locking should be
ok, correct? though it could potentially be ported to a system with very
weak memory model.
 
Daniel Jin said:
but if you are running the code on a x86 machine, double locking should be
ok, correct? though it could potentially be ported to a system with very
weak memory model.

I don't know whether it's definitely correct, even on x86. It may well
be, but I certainly wouldn't like to write a load of code assuming it.
You never know where your code will end up...
 
I don't know whether it's definitely correct, even on x86. It may well
be, but I certainly wouldn't like to write a load of code assuming it.
You never know where your code will end up...

CLI I 12.6.8 says:

"It is explicitly not a requirement that a conforming implementation
of the CLI guarantee that all state updates performed within a
constructor be uniformly visible before the constructor completes.
CIL generators may ensure this requirement themselves by inserting
appropriate calls to the memory barrier or volatile write
instructions. "

When I read this it tends to make me want to err on the safe side and
avoid the situation altogether. You never know what conforming
implementation your code might end up on...
 
Back
Top