Reputation: 330
I'm fairly new to C# and have been trying to learn for the last 3 days. I am curious as to why the below code is not working properly? I get the following error: Object reference not set to an instance of an object. when I try to call data.dOffsets["roomtargets"]. However, calling data.sProcessName does work without any error..
I have two classes/files. The program.cs:
class Program
{
public static Data data = new Data();
static void Main(string[] args)
{
Console.WriteLine("data.sProcessName: {0}", data.sProcessName);
Console.WriteLine("data.dOffsets[\"roomtargets\"]: {0}", data.dOffsets["roomtargets"]);
And the Data.cs:
public class Data
{
public string sProcessName { get; set; }
public Dictionary<string, int> dOffsets { get; set; }
public Data()
{
sProcessName = "Client";
Dictionary<string, int> dOffsets = new Dictionary<string, int>()
{
{"roomtargets", 0x0018FA48}
};
}
}
Any help would be greatly appreciated!
Upvotes: 2
Views: 7008
Reputation: 1380
Your dOffsets is local to the constructor. Your class already has that property, so you don't need declare another local variable there
public Data()
{
sProcessName = "Client";
dOffsets = new Dictionary<string, int>()
{
{"roomtargets", 0x0018FA48}
};
}
this should work
Upvotes: 1
Reputation: 125620
Dictionary<string, int> dOffsets = new Dictionary<string, int>()
{
{"roomtargets", 0x0018FA48}
};
This code initialize a dictionary as an inner variable within the constructor. Change it to:
dOffsets = new Dictionary<string, int>()
{
{"roomtargets", 0x0018FA48}
};
or this.dOffsets
to make it more clear.
Upvotes: 9