This is an array class that let the user choose the type of array ( string or int ). Am new to c# but am familiar with OOP, i didn't understand why i got this error
System.NullReferenceException: 'Object reference not set to an instance of an object.' mArr was null.
I have allocated memory for array of ( int[] type or string[] type ) based on " check " variable, so the array is there, it's not Null to my understanding. I choosed "int" just to test code.
problem on line 52.
1 using System;
2 public class TP1
3 {
4 public static void Main()
5 {
6 tableau tab = new tableau(10, "int");
7 tab.fillTab();
8 tab.printTab();
9 }
10 public class tableau
11 {
12 public
13 int mLength;
14 string mType;
15 int tmp;
16 string tmp2;
17 int[] mArr;
18 string[] mArr2;
19 int check;
20 public tableau(int n, string type)
21 {
22 this.mLength = n;
23 this.mType = type;
24 if (mType == "int")
25 {
26 check = 1;
27 int[] mArr = new int[mLength];
28 }
29 else if (mType == "string")
30 {
31 check = 2;
32 string[] mArr2 = new string[mLength];
33 }
34 }
35 public int getLength()
36 {
37 return mLength;
38 }
39 public string getType()
40 {
41 return mType;
42 }
43 public void fillTab()
44 {
45 if (check == 1)
46 {
47 Console.WriteLine("Entrez les valeurs de type int : ");
48 int i;
49 for (i = 0; i < getLength(); i++)
50 {
51 Console.WriteLine("Entrez la valeur {0}: ", i + 1);
52 mArr[i] = Convert.ToInt32(Console.ReadLine()); //Problem here
53 }
54
55 }
56 if (check == 2) "
57 {
58 Console.WriteLine("Entrez les valeurs de type string : ");
59 int i;
60 for (i = 0; i < getLength(); i++)
61 {
62 Console.WriteLine("Entrez la chaine {0]: ", i + 1);
63 mArr2[i] = Console.ReadLine();
64 }
65 }
66 }
67 public void sort()
68 {
69 if (check == 1)
70 {
71
72 for (int i = 0; i < getLength(); i++)
73 {
74 for (int j = i + 1; j < getLength(); j++)
75 {
76 if (mArr[j] < mArr[i])
77 {
78 tmp = mArr[i];
79 mArr[i] = mArr[j];
80 mArr[j] = tmp;
81 }
82 }
83 }
84 }
85 else if (check == 2)
86 {
87 for (int i = 0; i < getLength(); i++)
88 {
89 string temp = mArr2[i];
90 for (int j = i + 1; j < getLength(); j++)
91 {
92 string temp2 = mArr2[j];
93 if (string.Compare(temp, temp2) == 1)
94 {
95 tmp2 = mArr2[i];
96 mArr2[i] = mArr2[j];
97 mArr2[j] = tmp2;
98 }
99 }
100 }
101 }
102 }
103 public void printTab()
104 {
105 if (check == 1)
106 {
107
108 Console.WriteLine("\nTableau trié aprés insertion :");
109 for (int i = 0; i < mLength; i++)
110 {
111 Console.Write("{0} ", mArr[i]);
112 }
113 }
114 if (check == 2)
115 {
116
117 Console.WriteLine("\nTableau trié aprés insertion :");
118 for (int i = 0; i < mLength; i++)
119 {
120 Console.Write("{0} ", mArr2[i]);
121 }
122 }
123 }
124 }
125 }