How to resolve NullReference Exception on String Array Objects? [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I have a String array object in a class, i.e, String[] particulars which I want to initialize during runtime. The same code segment worked for another class object which was not array though. Here nd is an object of class.
int i=0;
foreach (DataRow row1 in dt1.Rows)
{
nd.particulars[i] = row1["floor"].ToString();
nd.quantity[i] = (double)row1["area"];
nd.rate[i] = (double)row1["rate"];
nd.amount[i] = (double)row1["amount"];
i++;
}
The following code is throwing some NullReferenceException. The error says:
Object reference not set to an instance of an object.
The class definition is as:
class NoteDetails
{
public string[] particulars;
public double[] quantity;
public double[] rate;
public double[] amount;
public string[] mparticulars;
public double[] mquantity;
public double[] mrate;
public double[] mamount;
public NoteDetails()
{
particulars = null;
quantity = null;
amount = null;
rate = null;
mparticulars = null;
mquantity = null;
mamount = null;
mrate = null;
}
}
Please tell me what I'm doing wrong?

You have to initialize your string array (and your others arrays too). You can do that on the constructor of the class.
nd.particulars = new string[5]; //or whatever size

*NullReferenceException** seems that one of your object is null ( nd or row1 or dt1 ). If something is null do not forget to instanciate it.
You need to debug your code to check where you have this issue.
Furthermore, you should test if your object are null to avoid this error like this :
if( dt1 != null ){
//do what you want
}
or like this (>= C#6 )
dt1?.Rows

Related

C# alternative to runtime optional parameters? [duplicate]

This question already has answers here:
Default parameter for value must be a compile time constant?
(7 answers)
Closed 5 months ago.
I'm not sure how to go about doing this, after a bit of research I couldn't really find something that fits my needs. The only thing I could find is from another coding language entirely. I think I might be over-complicating things but I'm blanking and can't seem to wrap my head around this problem.
Here's a simplified example of what I'm trying to achieve, say I have a class Item:
public class Item {
public int val { get; set; } = 1;
public void Link(Item i) { ... }
}
And in some other class that manages Items, I have this method:
void LinkPair(int val = GetLowestVal()) {
var pair = GetItems(val);
pair[0].Link(pair[1]);
}
Basically what I want it to do is: if given a value val, find and link a pair of Items with matching values, otherwise just link a pair both with the lowest value in the list. Unfortunately void LinkPair(int val = GetLowestTier()) isn't a valid signature. Also, since val is an int I can't set its default to null, otherwise I would so something like this I presume:
void LinkPair(int val = null) {
val = val ?? GetLowestVal();
...
I'd like to avoid having to create another overloaded method since I might end up with quite a few variations of these. Any help would be appreciated!
You can't assign null to an int. You'll have to use int?
void LinkPair(int? val = null) {
val = val ?? GetLowestVal();
If you know that val will never be 0 you can use this as the default :
void LinkPair(int val = 0) {
val = val!=0? val : GetLowestVal();
0 is the default for numbers so this is equivalent to :
void LinkPair(int val = default) {
val = val!=0 ? val : GetLowestVal();

C# run-time NullReferenceException when calling method [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
A newbie to C# here (more C++ for many years) struggling with perhaps a simple problem, but unable to diagnose.
Class definition:
public class myClass{
String prop1, prop2,... propn;
public void setValues(String input){
prop1 = input.Substring(1,5);
prop2 = input.Substring(6,10);
...
propn = input.Substring((n-1)*5+1,n*5));
}
public getProp1() {return prop1;}
public getProp2() {return prop2;}
...
public getPropn() {return propn;}
}
In program
myClass[] Entries = new myClass[50];
int i=0;
String Line
while(i<=49){
Line = inputFile.ReadLine(); //<--System.NullReferenceException thrown here at run-time
Entries[i++].setValues(Line);
}
Any help would be sincerely appreciated to figure out this run-time exception. I'm using Visual Studio 2019, and this is a console application...if that's relevant.
Thanks in advance!
This line:
myClass[] Entries = new myClass[50];
Creates an array filled with null's for values. So Entries[i++] will return you a null resulting in the error in your question. You can create an object of your type with new for example like this:
while(i<=49)
{
Line = inputFile.ReadLine();
var instance = new myClass();
instance.setValues(Line);
Entries[i++] = instance ;
}

Declare an array of queues [duplicate]

This question already has answers here:
All possible array initialization syntaxes
(19 answers)
Closed 5 years ago.
What is the language grammatical problem in my code?
I want to declare an array of queues. Is this the right way to declare and use them?
public static void Main(string[] args)
{
Queue<int>[] downBoolArray = new Queue<int>[8]();
downBoolArray[0].Enqueue(1);
}
Your first problem is a syntax error: new Queue<int>[8]() should be new Queue<int>[8].
Once declared with the correct syntax, when you attempt to use an element of the array (downBoolArray[0].Enqueue(1)) you will encounter a NullReferenceException because array elements initialise to their default values which in the case of a reference type is null.
You could instead initialise your array with non-null seed values using a single line of LINQ:
Queue<int>[] downBoolArray = Enumerable.Range(1,8).Select(i => new Queue<int>()).ToArray();
The arguments to Range specify that we need 8 'entries' in our sequence; the Select statement creates a new Queue<int> for each item; and the ToArray call outputs our sequence as an array.
You need to initialize each element in your array
void Main()
{
Queue<int>[] downBoolArray =new Queue<int>[10];
for (int i = 0; i < downBoolArray.Length; i++)
downBoolArray[i] = new Queue<int>();
downBoolArray[0].Enqueue(1);
}
You've created an array of null values.
What you want is something like this:
public static void Main(string[] args) {
var queues = new Queue<int>[8];
// Possibly some other stuff
// Initialise all values
for (var i = 0; i < queues.Length; i++) {
// Accounting for maybe already sporadically initialising values
queues[i] = (queues[i]) ?? new Queue<int>();
}
// Do whatever
}

Why is my C# object null after I have instantiated it? (Or have I not done that properly?)

Why is my C# object null after I have instantiated it?
I either don't know how to instantiate a class in C#, or there is a trick with 2D matrices that I'm missing here. (Either way I'm new to it all, and I limit myself to asking one question on Stack Overflow per day, so go easy with the downvotes...)
My program is a Win8 app.
I have a C# class with three members. They are:
class CMyClass
{
public double[][] matrix1;
public double[][] matrix2;
public double[][] matrix3;
}
And I try to instantiate it in my program like this:
CMyClass myObject = new CMyClass();
Then if I try to access any of the matrix members to read or write to the arrays I get a null reference exception error that say the object isn't instantiated. Is something missing from my class or is the problem with the way I try to instantiate the object?
Because you haven't instantiated those items yet.
class CMyClass
{
public double[][] matrix1;
public double[][] matrix2;
public double[][] matrix3;
public CMyClass()
{
matrix1 = new double[][] {};
matrix2 = new double[][] {};
matrix3 = new double[][] {};
}
}
Creating an instance of an object initializes its members to their default values. For reference types (like an array) this means null.
You need to explicitly create an empty array of the size you want in the objects constructor;
matrix1 = new double[4][2];
you can also put it in the declaration of the member (but that would be odd since you probagbly dont know what size you want - or maybe you do)
You have only instantiated the CMyClass, you haven't instantiated any of the members of the class.
Try adding a default constructor to the class, and in the constructor set the member values.
public CMyClass()
{
matrix1 = new double[][] {};
...
}
Just tried with tiny console app.
static void Main(string[] args) {
CMyClass myObject = new CMyClass();
myObject.matrix1= new double[1][] ;
myObject.matrix1[0] = new double[1];
Console.WriteLine(myObject.matrix1[0][0]);
}
Thanks folks. This seems to be the best working solution for me:
> class CMyClass
> {
> public double[][] matrix1;
>
> public CMyClass(int x)
> {
> matrix1 = new double[x][];
> for (int i = 0; i < x; i++)
> { matrix1[i] = new double[x]; }
> }
> }
Then in program:
int matrixSize = 10;
CMyClass MyNewObject = new CMyClass(matrixSize);
Now I can read and write to the elements of the matrix.
Solved! =D

C#: GetHashCode, Equals and Dictionary leads to IndexOutOfRangeException? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When does a dictionary throw an IndexOutOfRangeException on Add or ContainsKey?
This one is funky. I can't get to the bottom of it with ease. Found an exception in the log and dug out some old code. Don't ask me about why this is written this way because I have no idea. The question really is what could be conditions for IndexOutOfRangeException to be thrown when the Item of the dictionary is being set. Here is how the thing looks:
public MyEnum { Undefined = 0, B = 1, C = 2, D = 16, All = B | C | D }
public class MC
{
private int _hashCode;
private int _i;
private MyEnum _e;
public MC(int i, MyEnum e)
{
_i = i;
_e = e;
SetHashCode();
}
private SetHashCode()
{
_hashCode = _i * 31 + (int)e;
}
public override bool Equals(object other)
{
if (!(obj is MC))
{
return false;
}
MC other = (MC)obj;
return ((_i == other._i) && (_e == other._e));
}
public override int GetHashCode()
{
return _hashCode;
}
}
...
var d = new Dictionary<MC, DateTime>();
...
// Create and populate the list of MCs
var mcs = new List<MC>();
...
foreach (MC mc in mcs)
{
...
d[mc] = DateTime.UtcNow; // Pukes here
}
And the exception is:
System.IndexOutOfRangeException, Source: mscorlib Index was outside the bounds of the array. at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
Ideas how to make the line to fail? Don't what to diverge your attention to the wrong direction but I thought there was something fishy with the Equals and GetHashCode but I couldn't prove it so far - no repro using a unit testing framework.
The error you are getting is often caused by multi-threaded, un-locked concurrent access to a dictionary.
See: When does a dictionary throw an IndexOutOfRangeException on Add or ContainsKey?

Categories