This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
I have a static class:
public static class Options
{
public static MiscSettings MiscSettings;
public static Units Units;
}
My definitions for the two property classes looks like this:
[Serializable]
public class Units
{
public LengthUnit LengthUnit { get; set; } = LengthUnit.Millimeter;
public VolumeUnit VolumeUnit { get; set; } = VolumeUnit.CubicCentimeter;
}
[Serializable]
public class MiscSettings
{
public bool OutputDebugging { get; set; } = false;
}
When I do:
Options.Units = OptionsData.Units;
Options.MiscSettings.OutputDebugging = false;
The first line executes ok. The second gives me a NullReference Exception. The property Options.MiscSettings is null. The next error is Object not set to an instance of an object.
I've tried renaming everything, changing order of the properties. I also tried moving the property OutputDebugging to the Units class and that worked just fine.
Any help would be appreciated.
Just because a field is static doesn't mean you don't have to initialize it. Here, MiscSettings is never initialized, so it's null, and when you try to set its OutputDebugging you get the aforementioned NullReferenceException.
One easy way to to set OutputDebuggin would be to initialize MiscSettings with an object initializer:
Options.MiscSettings = new MiscSettings
{
OutputDebugging = false;
}
try this
if(Options.MiscSettings==null) Options.MiscSettings=new MiscSettings();
Options.MiscSettings.OutputDebugging = false;
When you are creating a class object, you need to make sure to initialize the variables you will use. The MiscSettings variable is not set, therefore you are getting a NullReferenceException.Options.MiscSettings = new MiscSettings();
Related
This question already has answers here:
Implicit typing; why just local variables?
(6 answers)
Closed 1 year ago.
I want to create an anonymous type in C# inside a class.
The examples I have seen use var to create an anonymous variable
var RecordId = new
{
Foo = 0,
Bar = "can be also a string"
};
However I want to create my anonymous variable inside a class.
public class Logger //: LogBase
{
var RecordId = new
{
Foo = 0,
Bar = 1
};
}
So when Logging I can do:
Logger.RecordId.Foo
But declaring my anonymous type as var triggers the following error:
CS0825: The contextual keyword 'var' may only appear within a local variable declaration.
What is the type of an anonymous variable, so I don't have to use var?
I understand what the error is telling me, but I don't want to move my variable inside a function, it needs to be a property of Logger.
Edit: enum is what I tried t the beginning, but I need the values to be more flexible than just integers (like strings, so I can dump jon files).
I updated my question to reflect that.
var (and by definition anonymous types) can only be declared inside a method, the error message is basically telling you that. If you need this type to be at class level, then make a class/struct/tuple to store it.
public static class Record
{
public static int Foo { get; set; }
public static int Bar { get; set; }
}
public class Logger //: LogBase
{
public static Record RecordId { get; set; } = new Record();
}
Now you can do this:
var foo = Logger.RecordId.Foo;
Note that I also used static so you don't need to create a new instance of the class, but change that if you think it's relevant.
public class Logger //: LogBase
{
public enum RecordId
{
Foo = 0,
Bar = 1
}
}
If you do not want strings you can do the above.
public class LogCategory
{
private LogCategory(string value) { Value = value; }
public string Value { get; private set; }
public static LogCategory Foo { get { return new LogCategory("Foo"); } }
public static LogCategory Bar { get { return new LogCategory("Bar"); } }
}
If you want strings you could create your own class something like the above.
You can use the dynamic type to have an anonymous instance variable.
public class Foo
{
dynamic bar = new {
A = 1,
B = 2
};
public void Print() {
Console.WriteLine(bar.A);
}
}
Try it out!
Just because you can do this doesn't mean it's a good idea. See DavidG's answer for an alternative using a strongly-typed object that will not require you to expose your code to the many problems associated with the dynamic type.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
Here request is the LIST with the "sortcolumns" property, so Initialy it "sortcolumns" is null so programmatically I am trying to assign a two values which are part of sort columns
request.SortColumns.Add( new SortColumn() { Name = "PolicyName", Direction = DirectionType.Descending });
I am always getting this error, please let me know why - Object reference not set to an instance of an object.
here
public class SortColumn
{
public string Name { get; set; }
public DirectionType Direction { get; set; }
}
You seemingly need to initialize the list before you start adding to it (once)
request.SortColumns = new List<SortColumn>();
This might be in the constructor of the request, it might be before you Add code, you might even make it a intialised property of the class itself
Example of Property Intialization
public class SomeRequest
{
public List<SortColumn> SortColumns {get;set;} = new List<SortColumn>();
...
Example of Constructor Intializer
public class SomeRequest
{
public SomeRequest()
{
SortColumns = new List<SortColumn>();
...
You need to initialise the property before you use it, try this:
request.SortColumns = new List<SortColumn>();
request.SortColumns.Add( new SortColumn() { Name = "PolicyName", Direction = DirectionType.Descending });
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Apologies for what is probably a dumb question, but I think I've boiled my code down the the core issues, of which there are two that are driving me nuts. I'd appreciate any assistance.
In the code below, the first issue is when my debug gets to the line 'bus[0]..' I get the 'Object reference not set to an instance of an object', even though I just instantiated the class in the previous line.
My next issue is that the 'SystemArrays' class is intended to be a repository, visible by all my classes (such as 'Solver'), where they can Get & Set its public properties. However, I can't figure how or where to instantiate the class to make it visible to everyone.
Any help would be greatly appreciated. Thanks.
public Form1()
{
InitializeComponent();
}
SystemArrays newArray = new SystemArrays();
private void button1_Click(object sender, EventArgs e)
{
Bus[] bus = new Bus[3];
bus[0].elementNum = 5;
bus[1].elementNum = 8;
bus[2].elementNum = 26;
newArray.buses[0].elementNum = bus[0].elementNum;
}
public class SystemArrays
{
public Bus[] buses { get; set; }
}
public class Bus
{
public int elementNum { get; set; }
}
public class Solver
{
// int x = newArray.buses[0].elementNum;
}
1. You are initializing the array, not initializing the objects inside the array and hence getting the Object reference not set to an instance of an object exception. So, you need to make a code change like
Bus[] bus = new Bus[3];
bus[0].elementNum = 5;
To
Bus[] bus = new Bus[3];
bus[0] = new Bus();
bus[0].elementNum = 5;
2. To make newArray public, set the right accessibility by specifying the correct protection level like public as you need to expose the class to other classes. Also, you can declare it as static if you need a single copy of newArray, though it is better if you create a get property for this kind of scenario.
public static SystemArrays newArray = new SystemArrays();
You are getting 'Object reference not set to an instance of an object' exception because that is exactly what is happening. You have created the array of 5 elements (busses), but you have not initialized them. After you create an array, all its items contain default value of the type of the array. In your case type of the array is Bus (reference type) and default value of all reference types is null
You can initialize values of your array by simply assigning:
bus[0] = new Bus();
The problem is that you're instantiating the array, but not the single instances.
You can use the following compact way:
var buses = new Bus[3] // instantiate an array object of size 3
{
new Bus() { elementNum = 5 }, // instantiate new Bus object
new Bus() { element = 8 }, // and here
new Bus() { elementNum = 26 } // and here
};
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have the following three classes defined.
public class FrequencyRecord
{
public double Frequency;
public int Duration;
}
public class EntryRecord
{
public string Name;
public Boolean Status;
public long TotalTime;
public FrequencyRecord[] FreqTime = new FrequencyRecord[25];
public string Description;
}
public class Salv7Profile
{
public string Version;
public string SoftVersion;
public string Name;
public DateTime CreateDate;
public DateTime LastModDate;
public int Count;
public EntryRecord[] Entries = new EntryRecord[99];
public int Type;
}
Then I create an instance:
public static Salv7Profile IntProfile = new Salv7Profile();
Assigning a value to:
IntProfile.Name = "Peter";
works fine, But if I try:
IntProfile.Entries[1].Name = "Peter";
It throws an error: [System.NullReferenceException] "Object reference not set to an instance of an object."}
Being a novice at C#, how do I access the nested Entries class?
The problem is that you've created an array, but that array is just full of null references to start with. You'd need something like:
EntryRecord record = new EntryRecord();
record.Name = "Peter";
IntProfile.Entries[1] = record;
to replace the array element with a reference to the newly-created EntryRecord.
It would almost certainly be better if you changed Entries to be a List<EntryRecord> though, and just used:
EntryRecord record = new EntryRecord();
record.Name = "Peter";
IntProfile.Entries.Add(record);
or more briefly, using an object initialzier:
IntProfile.Entries.Add(new EntryRecord { Name = "Peter" });
I would also strongly recommend against having public fields; use properties instead, and consider making your types immutable if you can.
(I'd encourage to think about whether you really need the IntProfile field to be static, too... static fields imply global state, which is harder to test and reason about.)
This question already has answers here:
What is the best way to give a C# auto-property an initial value?
(23 answers)
Closed 5 months ago.
Properties
public class student
{
public int id { get; set; }
public mark mark { get; set; }
}
public class mark
{
public int value { get; set; }
}
I'm creating object as below
student x=new student();
x.id=1 --> default value 0
but when i access x.mark.value it throwing exception(x.mark is null)
Doesn't initiate by default? any reason?
The default value for an automatic property is default(T), where T is the type. Since the default for any reference type is null, mark is null. Value types can never be null and, as you have noticed, default(int) is 0.
Default value for all reference types is null not 0. You should initialize it in your constructor:
public student()
{
mark = new mark();
}
When you try to access mark.value without initializing it you are trying to access a null object's property which is cause the NullReferenceException:
null.value = NullReferenceException!
See the documentation and this question for more details: What is a NullReferenceException and how do I fix it?
class is reference type, and all reference types resides in heap, their memory is allocated when you create object of it using new. So if you doesn't create new object i.e. you don't instantiate that class it will hold null i.e. no address is assigned to that class.
Variables in C# automatically take on their default values (which can be found by calling default on them - for example default(int).
The reason your ID variable is being intialised to zero is because the default of an int is 0.
The reason your Mark variable is being intialised to nullis because the default of any class is null.
Default value for reference types is null reference. Make your mark a struct if you want the behavior you described:
public struct mark
{
public int value { get; set; }
}
student x = new student();
x.id = 1;
x.mark.value = 5; // No exception thrown
As an alternative, just new your mark from within the constructor:
public student()
{
this.mark = new mark();
}
Hope this helps.
What you don't see, i guess, is that you are initializing student in fact, but not mark at all!
While initializing student by using
student s = new student();
s.id = 1;
All your properties would look like this:
id = 1
mark = null
If you would extend your constructor for student-class like this:
public class student
{
public student() {
this.mark = new mark();
}
public int id { get; set; }
public mark mark { get; set; }
}
You would reach your goal for a default value of 0 when calling
x.mark.value;
while your properties would look like this:
id = 1
mark = 0
i hope this might help you!
You are referring to the object instance mark which you do not initialize in your student class.
There are many options available for you. If you insist that they both should be classes, create a instance of Mark in default constructor of Student
public class Student
{
public Student()
{
this.mark = new Mark();
}
public int id { get; set; }
public Mark mark { get; set; }
}
public class Mark
{
public int value { get; set; }
}