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 ;
}
Related
This question already has answers here:
C# Copy Array by Value
(8 answers)
Copy one 2D array to another 2D array
(4 answers)
Closed 2 years ago.
This is an addendum to a previous question I asked about copying classes.
The basic answer to the previous question (copying classes not as reference type) was to use a memberwise clone method to avoid keeping links between the two classes.
Doing this on a class with only int values works, but this breaks apart as soon as I introduce arrays in the mix. See the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyClass
{
public int[] myNumber;
public MyClass ShallowCopy()
{
return (MyClass)this.MemberwiseClone();
}
}
public class Test : MonoBehaviour
{
Dictionary<string, MyClass> myDictionary1 = new Dictionary<string, MyClass>();
Dictionary<string, MyClass> myDictionary2 = new Dictionary<string, MyClass>();
void Start()
{
myDictionary1.Add("a", new MyClass() { myNumber = new int[] { 1, 1 } });
myDictionary1.Add("b", new MyClass() { myNumber = new int[] { 2, 2 } });
myDictionary2["b"] = myDictionary1["a"].ShallowCopy();
myDictionary2["b"].myNumber[0] = 3;
Debug.Log(myDictionary1["a"].myNumber[0]); //output 3, I'd want it to still be 1
}
}
I've tried implementing the ShallowCopy method (implemented in line 9 and used in line 25) and it doesn't work. I should implement a DeepCopy method, but I don't know how to formulate it applied to arrays.
My new DeepCopy function would be something like
public MyClass DeepCopy()
{
MyClass other = (MyClass)this.MemberwiseClone();
other.myNumber = ?????????????????????? //int[] deep copy
return other;
}
But I have no idea how to formulate a copy of the array. I've found a similar thread dealing with this, but I couldn't adapt the solution to my case.
Thanks in advance!
If you know that your array is going to be full of value types like int, or you have reference types and you want both arrays to refer to the same instance, you can use CopyTo
int[] copyTarget = new int[copyFrom.length];
copyFrom.CopyTo(copyTarget, 0);
If your array can/does have reference types in it, and you don't want the new array to reference the same instances, you will have to instead move through the elements doing a memberwise clone of each:
int[] copyTarget = new int[copyFrom.length];
for(int i = 0; i < copyTarget.Length; i++)
{
copyTarget[i] = copyFrom[i].MemberwiseClone();
}
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
first time posting on here and a bit of a noob in c#. Basically I'm creating a linkedlist and initializing it to null at the beginning of my class. When I'm ready to use it, I check to make sure that it's not equal to the string passed by the method. I immediately get a NullReferenceException, and i'm supposed to be comparing it to null. Any fixes?
private DoubleLinkedListCell<DoubleLinkedListCell<GamePiece>> _columns = null;
public void FindColumn(string columnId)
{
bool right = true;
while (_columns.Id != columnId)
{
if (_columns.Next == null)
{
right = false;
}
if (right)
{
Columns = Columns.Next;
}
else
{
Columns = Columns.Prev;
}
}
}
You will get null reference if u try to access any property or member of _columns List (ex _columns.Id,_columns.Next etc..) so initialize it in constructor or direct when u declare field
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
This question already has answers here:
Interesting "params of ref" feature, any workarounds?
(5 answers)
Closed 7 years ago.
I'm not sure if this is easy possible in C#. But I would like to get to know how this could be done easily.
public partial class Form1
{
// I left out the unimportant code for this example
private myControl cLeft,cTop,cBottom,cRight;
private List<myControl>mControls;
public Form1()
{
InitializeComponents();
//this list should contain the fields cLeft,cTop,cBottom,cRight...
mControls=new List<myControl>(){cLeft,cTop,cBottom,cRight};
/* now I want that cLeft and so on get assigned...
of course, this doesn't work because the list refers to the values of
cLeft ... which are null. So I would need to store a reference to those fields to get this work.*/
mControls.ForEach(x=>x=new myControl(this));
}
}
I'm sure it could be done through reflection, but I assume that there should be a way to do this easily in C# or isn't it possible?
It's just a simple loop, there is no need to use LINQ. You just need a for loop.
for (int i = 0 ; i < mControls.Count ; i++) {
mControl[i] = new myControl(this);
}
But, there is no need to write cLeft, cTop etc. You can just refer to them using the indexer: mControls[0], mControl[1] etc.
And remember, the foreach loop or the ForEach extension method doesn't work. This is because you are changing the reference of the variable. That is just another confusing (for beginners) feature of reference types!
Consider this method
public void ChangeReference (string s) {
s = "Hello";
}
And you call this method:
String s = "xxx";
ChangeReference (s);
Will s be "Hello" after the call? No. In the method, you are changing the location of the string in memory, but the argument is still in the same place!
This question already has answers here:
Object initializer performance
(7 answers)
Closed 9 years ago.
What is more efficent between this:
MyClass foo = new MyClass()
{
name = "foo",
color = "blue",
number = 3
};
and this:
MyClass foo = new MyClass();
foo.name = "foo";
foo.color = "blue";
foo.number = 3;
Difference between first and second is, that the second way won't create a temporary object (as explained here: CA2000 - "out-of-school-junior-programmers"-mistakes or false positive?) - so no problems, warning or errors when it comes to disposing My Class.