How can I solve Array with class problem? [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed last month.
I am new to c#, I try to check if array with a customized class could work.
As you see in my code, First Try is OK, but Second Try is NG.
Thanks a lot if someone show me a way to solve it.
static void Main(string[] args)
{
#First Try OK
string[] a = new string[2];
a[0] = "Jordan";
a[1] = "Pippen";
Console.WriteLine(String.Join(",", a));
#Second Try NG
player[] b = new player[2];
b[0].name = "Jordan"; ==> Object reference not set to an instance of an object
b[1].name = "Pippen";
Console.WriteLine(String.Join(",", b));
}
class player
{
public string name;
}
I except I can know more detail about array concept.

this code
#Second Try NG
player[] b = new player[2];
only creates an empty array of size 2. You need to create the player objects too
#Second Try NG
player[] b = new player[2];
b[0] = new player();
b[1] = new player();
b[0].name = "Jordan"; ==> Object reference not set to an instance of an object
b[1].name = "Pippen";

Related

Deep copy a class with arrays [duplicate]

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();
}

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

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

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

Adding CustomClassObjects to Dictionary as values

I have a task where I need to have two values for one key in Dictionary.
Solution found in web is to make new class with two fields and use it's objects as values.
But how can I assign value to my CustomClassObjects from Dictionary's for loop?
Here is the code:
Dictionary<char, Huffmans> HuffmanDictionary = new Dictionary<char, Huffmans>();
Program.text = File.ReadAllText(Program.sourcetext);
char character;
for (int i = 0; i < Program.text.Length; i++)
{
counter++;
character = Convert.ToChar(Program.text[i]);
if (HuffmanDictionary.ContainsKey(character))
HuffmanDictionary[character].probability++;
else
HuffmanDictionary.Add(character, 1);// here is the problem, obviously program can't assign value directly to class...
}
public class Huffmans
{
public int code = 0;
public double probability = 0;
}
Basically, I need to assign only "probability" values on this step. Should I call constructor for "Huffmans " on each iteration?
Big thanks for any help, Alex
You need to instantiate your class before adding the value:
HuffmanDictionary.Add(character, 1);
Should be:
HuffmanDictionary.Add(character, new Huffmans{ code = 1 });
Alternatively you can create a constructor for your class:
public class Huffmans
{
public Huffmans(int _code)
{
code = _code;
}
public int code = 0;
public double probability = 0;
}
then you can do:
HuffmanDictionary.Add(character, new Huffmans(1));
EDIT:
Some more clarification:
HuffmanDictionary.Add(character, 1);
fails because you are passing a type int into the dictionary but it is expecting the type Huffmans. Our dictionary is : Dictionary<char,Huffmans>()
HuffmanDictionary.Add(character, new Huffmans{ code = 1 });
works because now we are creating a new object of type Huffmans and we are setting the code value to 1.
Not sure if I understood your comment correctly, but effectively we are doing the same as:
var newHuffmans = new Huffmans{ code = 1 };
HuffmanDictionary.Add(character, newHuffmans);
But rather than writing out all that code and creating a named variable with our class, we skip this and pass it directly into the dictionary.

Categories