Initialized variable is null? - c#

I am trying to initialize a static variable from a static method but after it has been initialized it is still null. What am I doing wrong?
class Database {
public static Database Connection = null;
public static void Create() {
Database.Connection = new Database();
if (Database.Connection == null) {
Console.WriteLine("Null");
}
}
public Database() {
Console.WriteLine("I got called");
}
}
Am I missing something here? Database.Connection is NULL after calling the method although the constructor has been called.

class Database {
public static Database Connection = null;
static Database() {
Database.Connection = new Database();
if (Database.Connection == null) {
Console.WriteLine("Null");
}
}
public Database() {
Console.WriteLine("I got called");
}
}
You never call the Create(). You can use static constructor for this, if you'd like, as I've done above.

Use Static constructor, to initialize static field.
static Database()
{
Database.Connection = new Database();
}

One option is to make the static member a Property:
class Database
{
private static Database _connection = null;
public static Database Connection
{
get
{
if(null == _connection)
{
_connection = new Database();
}
return _connection;
}
}
}
If you are implementing a singleton, then you should hide the constructor by making it private.
private Database()
{
// This will only be called once, when the Connection
// property getter is first accessed and the private
// _connection field is still null. Note: when using
// the debugger, this may be before it is actually called
// explicitly from within your code!
Console.WriteLine("Database() constructor called");
}

Related

Entity framework context is not refreshing on modification

I have a WPF Project which is n-tier architecture and I use context per/call as it has Direct-database and web-service
Sorry a bit long question
Presentation => Business Layer => Data Layer
In datalayer i have UnitOfWork pattern implemented.
Initally when my DefaultAccessPoint was a Static property i had issues on multiple thread using the same context.
I had resolved it by changing the DefaultAccessPoint to a non-static property, and seems that multi thread issue had been Resolved .
after the fix =>(e.g) User could insert data into the Application on First tab(which takes approx. 3 mins) and simultaneously access the Second Tab(To fetch some data) while both are done in separate threads.
But after this Fix the Context doesn't refresh when a modification is done
The initial fix was done under DataProviderBase class were i changed static DataAccessPoint to Non-static and commented those lines that you see below.
How would i keep the context refresh with multi threading ?
Any Help is appreciated
Code Block
This is my dataproviderbaseclass every data-provider is inherited this base
public abstract class DataProviderBase
{
public DataProviderBase()
{
DefaultAccessPoint = new DataAccessAccessPoint(ConnectionString);
}
protected readonly ILogger logger = LoggerFactory.GetLogger();
private static string _connectionString;
public static string ConnectionString
{
get
{
return _connectionString;
}
set
{
_connectionString = value;
//COMMENTED as Fix for multiThreading
//_defaultAccessPoint = new DataAccessAccessPoint(ConnectionString);
}
}
private IDataAccessAccessPoint _defaultAccessPoint;
public IDataAccessAccessPoint DefaultAccessPoint
{
get
{
//COMMENTED as Fix for multi Threading
// Removed statis Default AccessPoint that was causing the issue
return _defaultAccessPoint; //?? (_defaultAccessPoint = new DataAccessAccessPoint(ConnectionString));
}
set { _defaultAccessPoint = value; }
}
}
This is my DataAccessPoint
public class DataAccessAccessPoint : IDataAccessAccessPoint
{
private string _connectionString;
public string ConnectionString
{
get
{
return _connectionString;
}
set
{
_connectionString = value;
}
}
private IDataContext context;
public DataAccessAccessPoint(string connectionString)
{
_connectionString = connectionString;
context = new MyDataContext(_connectionString);
}
public virtual bool Save()
{
return context.SaveChanges() > 0;
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
//Here i supply the context to my Data access layers
private IMyDataLayerDA _myDA;
public IMyDataLayerdDA MydDA
{
get { return _myDA ?? (_myDA = new MydDA(context)); }
set { _myDA = value; }
}
}
My DataProvider
public class PersonRoleDataProvider : DataProviderBase, IPersonRoleDataProvider
{
public MYDTOCLASS AuthenticateUser(string userId)
{
return DefaultAccessPoint.MydDA.AuthenticateUser(userId);
}
public IEnumerable<MYDTOCLASS> GetRoles(int personId)
{
return DefaultAccessPoint.MydDA.GetRoles(personId);
}
}
DataProviderAccessPoint
public class DataProviderAccessPoint
{
private static PersonRoleDataProvider _personRoleDataProvider;
public static PersonRoleDataProvider PersonRoleDataProvider
{
get
{
if(_personRoleDataProvider==null)
_personRoleDataProvider = new PersonRoleDataProvider();
return _personRoleDataProvider;
}
}
}

C# Use instantiated class in a different class/file

Am I able to use an instance of once class in another class and file without having to reinstantiate it?
class Start
{
public static Log Log = new Log(...);
}
class Start1
{
Log.Write("New instance!");
}
I have read about having to use a get/set block to do it, but I'm not exactly sure how I would go about that,
Singleton pattern:
public class Log
{
private static Log instance;
private Log() { }
public static Log Instance
{
get
{
return instance ?? (instance = new Log());
}
}
}
Use it by calling Log.Instance, and so on.
To call this using a parameter, you need to do something like this:
public class Log
{
private string foo;
private static Log instance;
public static Log Instance
{
get
{
if (instance == null)
{
throw new InvalidOperationException("Call CreateInstance(-) to create this object");
}
else
{
return instance;
}
}
}
private Log(string foo) { this.foo = foo; }
public static Log CreateInstance(string foo)
{
return instance ?? (instance = new Log(foo));
}
}
However, it is generally a bad idea to use singletons in this manor. Have a look at dependency injection / inversion of control to see how this can be solved.

Why is FieldInfo.GetValue(null) not working in static constructor

See the code below. I want a class that automatically enumerates all the defined static readonly instances of its own type (see TestClass as an example, it defines 3 static readonly instances of its own type).
I want this automation because I want to loop over the defined types and not risk the change of forgetting to add a new instance to the list of All.
Ok, I have it working, that is not the point. But why doesn't FillAll work when called from a static constructor? See the commented static constructor in DefinedInstancesBase<T> code. I mean FieldInfo.GetValue(null) returns null in the static constructor, though the debugger has already hit creating the static readonly instances before the FieldInfo.GetValue(null) is called.
I'm very curious why it doesn't work. Is this by design?
public abstract class DefinedInstancesBase<T>
{
public static IList<T> All
{
get
{
if (_All == null)
{
FillAll();
}
return _All;
}
}
//Why this doesn't work? No idea.
//static DefinedInstancesBase()
//{
// FillAll();
//}
private static void FillAll()
{
var typeOfT = typeof(T);
var fields = typeOfT.GetFields(BindingFlags.Public | BindingFlags.Static);
var fieldsOfTypeT = fields.Where(f => f.FieldType == typeOfT);
_All = new List<T>();
foreach (var fieldOfTypeT in fieldsOfTypeT)
{
_All.Add((T)fieldOfTypeT.GetValue(null));
}
}
private static List<T> _All = null;
}
[TestClass]
public class DefinedInstancesTest
{
[TestMethod]
public void StaticReadOnlyInstancesAreEnumerated()
{
//Given
var expectedClasses = new List<TestClass>
{
TestClass.First,
TestClass.Second,
TestClass.Third,
};
//When
var actualClasses = TestClass.All;
//Then
for (var i=0; i<expectedClasses.Count; i++)
{
Assert.AreEqual(expectedClasses[i].Id, actualClasses[i].Id);
}
}
private class TestClass : DefinedInstancesBase<TestClass>
{
public static readonly TestClass First = new TestClass(1);
public static readonly TestClass Second = new TestClass(2);
public static readonly TestClass Third = new TestClass(3);
public int Id { get; private set; }
private TestClass(int pId)
{
Id = pId;
}
}
}
There are two separate issues at work here.
There is a typo in your static constructor in the code above. Try changing static DefinedInstances() to static DefinedInstancesBase(), because currently it is just specified as a private static function.
The second and more important issue is to understand the order that the various constructors are being called in. What is happening is that the static constructor on the base abstract class is getting triggered by the instantiation (during member initializer) of the First field in the derived class. Therefore, First is still null when the static constructor of DefinedInstancesBase class is being called (and thus the FindAll() method).
See the following code (slightly modified to better illustrate the issue) and output:
public void Main()
{
DefinedInstancesTest dit = new DefinedInstancesTest();
dit.StaticReadOnlyInstancesAreEnumerated();
}
public abstract class DefinedInstancesBase<T>
{
public static IList<T> All
{
get
{
//if (_All == null)
// FillAll();
return _All;
}
}
// correctly named static ctor
static DefinedInstancesBase() { FillAll(); }
private static void FillAll()
{
Console.WriteLine("FillAll() called...");
var typeOfT = typeof(T);
var fields = typeOfT.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var fieldsOfTypeT = fields.Where(f => f.FieldType == typeOfT);
_All = new List<T>();
foreach (var fieldOfTypeT in fieldsOfTypeT)
{
_All.Add((T)fieldOfTypeT.GetValue(null));
}
}
private static List<T> _All = null;
}
//[TestClass]
public class DefinedInstancesTest
{
//[TestMethod]
public void StaticReadOnlyInstancesAreEnumerated()
{
//Given
var expectedClasses = new List<TestClass>
{
TestClass.First,
TestClass.Second,
TestClass.Third,
};
//When
var actualClasses = TestClass.All;
//Then
for (var i=0; i<expectedClasses.Count; i++)
{
//Assert.AreEqual(expectedClasses[i].Id, actualClasses[i].Id);
if (expectedClasses[i].Id != actualClasses[i].Id)
Console.WriteLine("not equal!");
}
}
private class TestClass : DefinedInstancesBase<TestClass>
{
public static readonly TestClass First;
public static readonly TestClass Second;
public static readonly TestClass Third;
public int Id { get; private set; }
static TestClass()
{
Console.WriteLine("TestClass() static ctor called...");
First = new TestClass(1);
Second = new TestClass(2);
Third = new TestClass(3);
}
private TestClass(int pId)
{
Console.WriteLine("TestClass({0}) instance ctor called...", pId);
Id = pId;
}
}
}
TestClass() static ctor called...
// the line "First = new TestClass(1);" now triggers the base class static ctor to be called,
// but the fields First, Second, and Third are all still equal to null at this point!
FillAll() called...
TestClass(1) instance ctor called...
TestClass(2) instance ctor called...
TestClass(3) instance ctor called...
// this null reference exception to be expected because the field value actually was null when FindAll() added it to the list
Unhandled Expecption:
System.NullReferenceException: Object reference not set to an instance of an object.

Singleton class for an object with parameters

I realized that I should have only one instance of an object called StdSchedulerFactory running at a time. So far I instantiated the object like this
StdSchedulerFactory sf = new StdSchedulerFactory(properties);
And properties is a NameValueCollection.
How can I write a Singleton class for this object so that the variable sf will always have one instance throughout the program?
Part of the Singleton pattern is typically a private constructor, so that other classes can not make new instances.
The workaround for parameters coming from outside the class is to add a "Init" or "Configure" function:
public static void Configure(NameValueCollection properties)
{
}
Of course, if you forget to call this function, you may get behavior you don't want; so you may want to set a "Configured" flag or something like that so your other functions can react appropriately if this function has not yet been called.
Here is a basic Singleton implementation. It is not thread-safe.
public sealed class StdSchedulerFactory
{
private static readonly StdSchedulerFactory instance;
private NameValueCollection _properties;
private StdSchedulerFactory(NameValueCollection properties)
{
_properties = properties;
}
public static StdSchedulerFactory GetInstance(NameValueCollection properties)
{
if (instance == null)
{
instance = new StdSchedulerFactory(properties);
}
else
{
return instance;
}
}
}
this is my two favorite way implementing simple singleton pattern. The second one is just easier when debugging :)
public sealed class SingletonOne
{
private static readonly Lazy<SingletonOne> instance = new Lazy<SingletonOne>(() => new SingletonOne());
private Lazy<Controller> controller = new Lazy<Controller>(() => new Controller(properties));
private static object properties = null;
public static SingletonOne Instance { get { return instance.Value; } }
public Controller GetController(object properties)
{
SingletonOne.properties = properties;
return this.controller.Value;
}
}
public sealed class SingletonTwo
{
private static readonly SingletonTwo instance = new SingletonTwo();
private Controller controller;
private static object properties = null;
public static SingletonTwo Instance
{
get
{
return SingletonTwo.instance;
}
}
public Controller GetController(object properties)
{
SingletonTwo.properties = properties;
if(this.controller == null)
{
this.controller = new Controller(SingletonTwo.properties);
}
return this.controller;
}
}
public class Controller
{
public Controller(object properties) { }
}

Singleton pattern for a property in c#

I am trying to adapt singleton policy for my CsvConfiguration Property.
If the configuration is already available, just return the configuration. else, get the configuration and return the same and I am able to build this code.
public Rootpdf pdfConfiguration
{
get
{
Rootpdf pdfConfiguration = null;
try
{
if (pdfConfiguration == null)
{
//retrieve the configuration file.
//load the configuration and return it!
}
else
{
return pdfConfiguration;
}
}
catch (Exception e)
{
Log.Error("An error occurred while reading the configuration file.", e);
}
return pdfConfiguration;
}
}
Advantages (i hope): Whenever my pdfConfiguration is wanted, if already it is available, i can return it. Need not load the configuration file eachtime
and calculate the configuration.
My Query: The resharper! The resharper tells that the code
if (pdfConfiguration == null) //The expression is always true.
Is it really a problem with resharper that it doesn't understand I am following this singleton pattern ?
or
Am I not following singleton pattern at all?
You're setting the singleton to null at the top of your get clause:
Rootpdf pdfConfiguration = null;
//THIS IS THE PROBLEM.
Note: 99% of the time, ReSharper is smarter than you. I don't like it, but it's true.
think you have to use a local variable out of the getter
private static Rootpdf _pdfConfiguration ;
public static Rootpdf pdfConfiguration
{
get
{
try
{
if (_pdfConfiguration == null)
{
//retrieve the configuration file.
//load the configuration and return it!
}
else
{
return _pdfConfiguration;
}
}
catch (Exception e)
{
Log.Error("An error occurred while reading the configuration file.", e);
}
return _pdfConfiguration;
}
}
and as you want a singleton, i made it a static property... hope it's what you need.
Here is what your class should look like:
public class RootPdf
{
private static RootPdf instance;
private RootPdf()
{
//retrieve the configuration file.
//load the configuration and return it!
}
public static RootPdf Instance
{
get
{
if (instance == null)
{
try
{
instance = new RootPdf();
}
catch (Exception e)
{
Log.Error("An error occurred while reading the configuration file.", e);
return null;
}
}
return instance;
}
}
}
And here is how you will call the object:
var pdf = RootPdf.Instance;
class MySingletonClass
{
private static UserSettings instance = null;
/// <summary>
/// Default protected constructor.
/// </summary>
protected MySingletonClass()
{
}
/// <summary>
/// Invoke the singleton instance.
/// </summary>
public static MySingletonClass Instance()
{
if (instance == null)
instance = new MySingletonClass();
return instance;
}
}
This woud be invoked/instanciated like
MySingletonClass msc = MySingletonClass.Instance();
You can also use an accessor/Property to return the instance
public MySingletonInstance Instance
{
get
{
if (instance == null)
instance = new MySingletonInstance();
return instance;
}
}
Where this is invoked/instantiated via
MySingletonClass msc = MySingletonClass.Instance;
I like the first method of the above.
I hope this helps.
As already mentioned this is a not a singleton pattern.
If you want to stick with the idea you described then I would change your code to :
internal class Config
{
private readonly Lazy<Rootpdf> _config;
public Config()
{
_config = new Lazy<Rootpdf>(ReadConfiguration);
}
private Rootpdf ReadConfiguration()
{
throw new NotImplementedException();
}
public Rootpdf pdfConfiguration
{
get
{
try
{
return _config.Value;
}
catch (Exception e)
{
Log.Error("An error occurred while reading the configuration file.", e);
}
return null;
}
}
This line: if (pdfConfiguration == null) will always be true due to this line (just before) Rootpdf pdfConfiguration = null;. What you need to do is to place the last line (Rootpdf pdfConfiguration = null;) outside the Get method. This will stop the variable to be initialized to null each time.
private static Rootpdf pdfConfiguration = null;
public Rootpdf PdfConfiguration
{
get
{
try
{
if (pdfConfiguration == null)
....
More information on the Singleton Pattern is available here.
Alternatively, you can use a Static Constructor:
A static constructor is used to initialize any static data, or to
perform a particular action that needs to be performed once only. It
is called automatically before the first instance is created or any
static members are referenced.
public class Foo {
private static Rootpdf pdfConfiguration = null;
static Foo()
{
pdfConfiguration = ....
}
public Rootpdf pdfConfiguration
{
get
{
return pdfConfiguration;
}
....
Nowadays , I think since C# 6.0, you can use initial values with properties, like this:
static public Rootpdf pdfConfiguration { get; } = new Func<Rootpdf>(() => {
//retrieve the configuration file.
//load the configuration and return it!
return new Rootpdf(); // Something like this perhaps..?
})();

Categories