IndexOutOfRange exception [duplicate] - c#

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 8 years ago.
Why is this giving a IndexOutOfRange exception?
string[] achCheckStr = File.ReadAllLines("achievements.txt");
if (achCheckStr[0] == ach1_StillBurning) // this is where the exception occurs
{
setAchievements(1);
}
if (achCheckStr[1] == ach2_Faster)
{
setAchievements(2);
}

Problem 1:
there mightbe no file exists with name achievements.txt.
this statement string[] achCheckStr = File.ReadAllLines("achievements.txt"); might be returning null.
Solution 1: so before accessing any files please check whether file exists or not by using File.Exists() method.
Problem 2: there might be no lines in your text file.
Solution 2: before accessing the string array which contains lines please make sure that it is not empty by checking its Length
Try This:
if(File.Exists("achievements.txt"))
{
string[] achCheckStr = File.ReadAllLines("achievements.txt");
if(achCheckStr.Length > 0)
{
if (achCheckStr[0] == ach1_StillBurning)
{
setAchievements(1);
}
if (achCheckStr[1] == ach2_Faster)
{
setAchievements(2);
}
}
}

Your code is assuming that the achCheckStr array has at least 2 elements without first checking how many there are. If the file exists & the contents are empty, achCheckStr.Length will be 0 and the IndexOutOfRangeException will be thrown exactly where it's happening.

Where are you storing "achievements.txt"? It could be in the wrong place, so the code would not find it.
You can fully qualify the path or put the file within the bin directory where the .exe is generated.

Here's a way
string[] achCheckStr = File.ReadAllLines("achievements.txt");
if (achCheckStr != null && achCheckStr.Any())
{
if (achCheckStr[0] == ach1_StillBurning) // this is where the exception occurs
{
setAchievements(1);
}
if (achCheckStr[1] == ach2_Faster)
{
setAchievements(2);
}
}

Related

Try statement doesn't always run? [duplicate]

This question already has answers here:
Use of unassigned local variable with try-catch-finally
(4 answers)
Closed last year.
i encountered an error "Use of unassigned variable 'attempt'" when i run the code below, i don't understand the reason because as i understand the try statement block always runs so the variable should be assigned by the user ? Or am i wrong ? If anyone has i fix or work around that would be helpful.
static void MagicNumber(int rndMin, int rndMax, int lives = 4)
{
Random rnd = new Random();
int rndNum = rnd.Next(rndMin, rndMax);
int attempt;
do
{
try
{
Console.WriteLine($"Remaining lives : {lives}");
Console.WriteLine($"Enter a number between {rndMin} and {rndMax} :");
attempt = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Error : Enter a number !");
}
} while ((lives > 0) || (attempt < rndMin) || (attempt > rndMax));
}
MagicNumber(1, 40, 5);
The variable attempt will not get assigned a value if an exception gets thrown in your try block, so will be unassigned when it gets to the evaluation in your while. The two possible solutions are:
Initialize it to a default value when you declare it.
Assign it some value in your catch block.
Either one should work.
An exception can be thrown in the try block prior to setting a value for attempt. You handle the exception so it's then possible for attempt to be referenced before being assigned a value.
Best practice is to always assign an initial value to variables.

How can i validate if List<int> is empty? [duplicate]

This question already has answers here:
Check if list is empty in C#
(8 answers)
Closed 3 years ago.
This is my Code:
public int PostCanal(List<int> listchannel) {
if (listchannel == null || listchannel.Contains(0))
{
listchannel.Add(1);
}
This list has values coming from a checkbox menu. So, if the user uncheck all the options I want to still using "1" as default value.
On this case, the listchannel List<int> is arriving with [0] value. However the if condition is skipped.
Any idea? Also tried .Equals Method.
You could use Any Or Count to check if the list is empty or not, like the following code :
if(listchannel == null || !listchannel.Any())
{
}
//Or
if(listchannel == null || listchannel.Count == 0)
{
}
I hope you find this helpful.

Getting a NullReferenceException when trying to compare to null [duplicate]

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

Unassigned Local Variable Error [duplicate]

This question already has answers here:
C# error: Use of unassigned local variable
(4 answers)
Closed 6 years ago.
So I have a folder with only 2 text files, I am reading them and storing the value. This is what the code looks:
public static void UnionFiles()
{
var dinfo =
new DirectoryInfo(
#"\http");
var files = dinfo.GetFiles("*.txt");
int i = 1;
System.Collections.Generic.IEnumerable<String> _eValA, _eValB;
foreach (var file in files)
{
if (i == 1)
{
_eValA = File.ReadLines(file.Name);
++i;
}
else
{
_eValB = File.ReadLines(file.Name);
i = 1;
}
}
IEnumerable<String> union = _eValA.Union(_eValB);
File.WriteAllLines(#"\http\union.txt", union.Cast<String>());
}
But I get this error: Use of unassigned local variable '_eValB, _eValA'
How can I get past it.
Thanks.
The first time through your loop, you will never have both _evalA and _evalB assigned. You need to assign to both to avoid that problem.
There are other related issues. For example, what happens when there aren't exactly two files?
Since there are exactly two files, you shouldn't need to use a loop. If you avoid the loop, you can easily avoid your current issue. For example:
var files = dinfo.GetFiles("*.txt");
System.Collections.Generic.IEnumerable<String> _eValA, _eValB;
// Should really assert that files.Count == 2
_evalA = File.ReadLines(files.First().Name);
_eValB = File.ReadLines(files.Last().Name);
IEnumerable<String> union = _eValA.Union(_eValB);
Think about the possible paths that your code could take. It's possible that _eValA may not be initialized, or that _eValB may not be initialized, and thus you would get an error. Since the compiler can detect this, it gives you a compilation error. You need to make sure they get set equal to a value (or null, which lets the compiler know you're taking responsibility for them, as explained here, but note null wouldn't be appropriate in this case because with 0 or 1 files you'd get an ArgumentNullException at the .Union call) before utilizing them. Try:
var _eValA = new string[0];
var _eValB = new string[0];
foreach (var file in files)
{
if (i == 1)
{
_eValA = File.ReadLines(file.Name);
++i;
}
else
{
_eValB = File.ReadLines(file.Name);
i = 1;
}
}
This will ensure they both get initialized before getting used.

Is there any way to check for string either it is null or blank? [duplicate]

This question already has answers here:
Easier way of writing null or empty?
(7 answers)
Closed 9 years ago.
Is there any way to check for string either it is null or blank("") in c#?
Currently I have to check two conditions first for null and other for blank value
if(val == "" || val == null)
{
return true;
}
You can use String.IsNullOrEmpty() method which checks for string references that are null or have no data:
if(String.IsNullOrEmpty(val))
{
return true;
}
There is also a method String.IsNullOrWhitespace() which indicates whether a specified string is null, empty, or consists only of white-space characters.
if(String.IsNullOrWhitespace(val))
{
return true;
}
The above is a shortcut for the following code:
if(String.IsNullOrEmpty(val) || val.Trim().Length == 0)
{
return true;
}
You can use String.IsNullOrEmpty method.
Indicates whether the specified string is null or an empty string.
if(String.IsNullOrEmpty(val))
{
return true;
}
There is easiest and simple way.
if (string.IsNullOrEmpty("Val")) //This condition comparing both NULL and EMPTY also
{
}
.Net has provided default function for this purpose you should use like this.
if (string.IsNullOrEmpty("any string"))
{
}
You can use String.IsNullOrEMpty.

Categories