I’m very new to C# and currently I’m using this way to always use the same instance:
public class Sample{
private Sample(){
//initialize sth.
}
private static Sample _instance;
public static Sample Instance{
get{
if(_instance == null)
_instance = new Sample();
return _instance;
}
}
}
Do you know a better way because it doesnt seem quite object-orientated to me…
The answer to your question is dependant on how you intend on using the property. Generally having a single static property across your full app is considered a bad idea as it can cause a lot of headaches when it comes to things like multi-threading environments/unit testing etc. However, there are scenarios where it is in-fact the correct approach e.g. logging.
Alternatively, you could use another approach where you pass the instance around to whoever needs it – more commonly know as Dependency Injection.