c#/.net: what happens when a class is instantiated?

fsm priest

New member
we have a few classes that have some pretty heavy stuff going on in their constructors. since they're instantiated in multiple methods within another class, but not always used, it didn't make sense to me to declare them as new at module level bcuz i didn't want all the initialization stuff in the constructor to run if the class wasn't going to be used. so i got creative and made this class:

public class Instantiator<ObjectType> where ObjectType : new()
{
private ObjectType _ObjectType;
public ObjectType Value
{
get
{
if (_ObjectType == null)
_ObjectType = new ObjectType();
return _ObjectType;
}
}
}

basically, it works like this:

Instantiator<ProxyService> ProxyService = new Instantiator<ProxyService>();

this way, the constructor of the generic type is used only if the .Value property is accessed. it has worked very well, but now the Instantiator class is being used everywhere in the project, even on classes that have no code in the constructor or even no constructor at all.

i want to clean it up and remove the Instantiator class where it is not needed, but, before i do, i'd like to know if it's still helping at all. my question is this: what happens when an instance of a class is first created even if it has no constructor or no code in its constructor? is there a performance gain in having a lightweight "encapsulator class" like the Instantiator as opposed to just automatically instantiating everything from the get-go even if they're no needed?
 
Back
Top