This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
I have IDictionary<string, int>. I need to get keys and values from dictionary in string format and add into string[] array. I need to do it because I want to pass that text in function and that function takes string array.
I have that code for getting value:
foreach (KeyValuePair<string, int> kvp in dict)
{
dataList.Add(kvp.Key + " " + kvp.Value.ToString());
}
I've created list and add in that list keys and values. After I was thinking to create for loop and from list add elements into array, but have error. Loop:
string[] txtArr;
for (int i = 0; i < dataList.Count; i++)
{
txtArr[i] = dataList[i];
}
Error: System.NullReferenceException. I don't understand where is the problem. From what I read about that error, I understood it raised because something is null. But if I'm trying print in console dictionary or list all is OK, there isn't null, also i is int and = 0. Where is the problem?
Your array is not instantiated, dude:
string[] txtArr = new string[dataList.Count];
for (int i = 0; i < dataList.Count; i++)
{
txtArr[i] = dataList[i];
}
or you can do it like this:
string[] txtArr = dataList.ToArray();
or you can do it like this:
string[] txtArr = dict.ToList().Select(x => x.Value).ToArray();
You have to initialize the string array.
string[] txtArr = new string[dataList.Count];
This question already has answers here:
string.Replace (or other string modification) not working
(4 answers)
Closed 3 years ago.
I want to replace characters in a string iteratively using the string.Replace() function in a for loop however every iteration the string itself resets and no changes made in the previous loop stay. Ending up in the string undergoing no changes overall.
I've tried making the string a class member but that didn't work,
static void Main(string[] args)
{
int i;
string strOne = "abcdefg";
for (i=0; i < (strOne.Length - 1); i++)
{
string c = Convert.ToString(strOne[i]);
strOne.Replace(c, "1");
}
}
I expect the output of 1111111 but instead i get abcdefg.
When you call string.Replace(), it does not modify the string itself. Instead, it returns the string with the replaced characters. Therefore, you need to do this: strOne = strOne.Replace(c, "1");
This question already has answers here:
C# multidimensional arrays iteration
(5 answers)
Closed 2 years ago.
I am trying to print out my array of numbers that I have assigned to a particular array. My algorithm for choosing numbers consists of choosing a random number that is not a duplicate and storing it inside the array.
Pretty simple really, but I have no idea as to why it is printing out this error.
int[] ticket1 = new int[4];
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
}
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1.ToString());//ticket1 produces System.Int32[] instead of 4 numbers.
//I have changed this line to:
//Console.WriteLine("{0}{1}", item.PadRight(20), string.Join(",", ticket1));
//And it still doesn't work. the error remains. (System.Int32[])
My question is, how can I print out my 4 numbers (beside each other) in string format.
//EDIT: I've found my problem. I am putting my ticket1 inside a foreach loop, it's somehow not reaching out to the array values and it therefore prints out System.Int32[] instead.
All fixed.
If you call ToString() on an array like that, you simply get the full name of the type of class.
You could fix it a few ways. Print only the current item inside the loop, or print each item one at a time outside of the loop:
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1[0]);
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1[1]);
// etc...
Or "flatten" the collection before printing:
Console.WriteLine("My numbers: ", String.Join(", ", ticket1));
ticket1.ToString() does not print the content of the array, only its type, because this is the way the ToString() method is implemented on arrays.
You can fix this in several ways - for example, by using string.Join method:
Console.WriteLine("{0}{1}", item.PadRight(20), string.Join(",", ticket1));
Because you are not writing your array elements, you are writing your array itself, that's why ToString() generates it's full type name.
Change your ticket1.ToString() to ticket1[i] in your for loop.
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
Console.WriteLine("{0} {1}", item.PadRight(20), ticket1[i]);
}
If you don't want to print it inside your for loop, then you can use String.Join to concatenate all your elements in your array in a simple string like;
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
}
Console.WriteLine("{0} {1}", item.PadRight(20), string.Join(",", ticket1));
Because when you call .ToString() on an object you get the type of that object. For basic primitive (value) types this behavior is overridden to output the value. But for something like an array there's no "default" string representation, so the behavior you're seeing is the default.
You could wrap your data in an object and override .ToString() on that object. If you have to output the values in many places in the code that would be the way to go so you only have to write the logic once. ("Smart data structures and dumb code works a lot better than the other way around." - Eric Raymond)
But if you only need to do it here then you can just output the values directly. Basically join the values as a string in whatever representation you want. For example, if they should be comma-separated:
Console.WriteLine(
"{0}{1}",
item.PadRight(20),
string.Join(",", ticket1));
This question already has answers here:
Adding values to a C# array
(26 answers)
Closed 9 years ago.
How can i create a int array in class.
And i have to add values to that array.
Not to a specific key.
i declared array as
public int[] iArray;
from function i have to insert values of i to array. My i values gets change. So i have to save those in a array.
iArray[] = i;
But it shows error.
Handling arrays is pretty straight forward, just declare them like this:
int[] values = new int[10];
values[i] = 123;
However, arrays in C# have fixed size. If you want to be able to have a resizeable collection, you should use a List<T> instead of an array.
var values = new List<int>();
values.Add(123);
Or as a class property:
class SomeClass
{
private List<int> values = new List<int>();
public List<int> Values { get { return this.values; } }
}
var someInstance = new SomeClass();
someInstance.Values.Add(123);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Remove element of a regular array
I have a method defined which returns class array.
ex: Sampleclass[]
The Sampleclass has properties Name, Address, City, Zip. On the client side I wanted to loop through the array and remove unwanted items. I am able to loop thru, but not sure how to remove the item.
for (int i = 0; i < Sampleclass.Length; i++)
{
if (Sampleclass[i].Address.Contains(""))
{
**// How to remove ??**
}
}
Arrays are fixed size and don't allow you to remove items once allocated - for this you can use List<T> instead. Alternatively you could use Linq to filter and project to a new array:
var filteredSampleArray = Sampleclass.Where( x => !x.Address.Contains(someString))
.ToArray();
It's not possible to remove from an array in this fashion. Arrays are statically allocated collections who's size doesn't change. You need to use a collection like List<T> instead. With List<T> you could do the following
var i = 0;
while (i < Sampleclass.Count) {
if (Sampleclass[i].Address.Contains("")) {
Sampleclass.RemoveAt(i);
} else {
i++;
}
}