Preventing Index Out of Range Error - c#

I want to write a check for some conditions without having to use try/catch and I want to avoid the possibilities of getting Index Out of Range errors
if (array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
So the problem I am facing is that in the second check I need to see whether I have one Item that is not empty. However, If I don't have Element[1], I get the Index Out of Range exception. The problem is that there could be 2 Elements and one(or both) of them may have empty Object arrays. The code will have to be executed only if one of thos Item strings is not empty.
Hopefully, I explained it well. How do I go about avoiding getting that exception under any condition?

Alright, you need some better null checking and some more cautious code here.
if (array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
is just unacceptable.
First, let's null check
if (array != null)
{
if (array.Element != null)
for simplicity, you could use &&
if (array != null && array.Element != null)
then, inside that if, we use a for loop (since you're stuck on arrays) and null check it
for (int i = 0; i < array.Element; ++i)
{
if (array.Element[i] != null && array.Element[i].Object != null)
{
then, since you have nested arrays, we loop again. This is called a nested loop, and it's generally bad practice, I'll show you why it works in a second.
for (int o = 0; o < array.Element[i].Object.length; ++o)
{
if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
{
Now, with all of that ugly nested loopyness, we've found out that your Item is not null.
On top of that, you have access to ALL of the potential values here, and can group them as you like. Here's how I would put the whole thing together for simplification.
List<string> arrayValues = new List<string>();
if (array != null && array.Element != null)
{
for (int i = 0; i < array.Element.length; ++i)
{
//bool found = false;
if (array.Element[i] != null && array.Element[i].Object != null)
{
for (int o = 0; o < array.Element[i].Object.length; ++o)
{
if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
{
arrayValues.Add(array.Element[i].Object[o].Item);
//if you want to drop out here, you put a boolean in the bottom loop and break and then break out of the bottom loop if true
//found = true;
//break;
}
}
}
//if (found)
// break;
}
}
if (arrayValues.Count > 0)
{
//do stuff with arrayValues
}

Could use a LINQ method ElementAtOrDefault(index)
so if the element is not found it will be null.
var currentElem = Elems.ElementAtOrDefault(i);
if(currentElem != null)
// do something
else
// do something

Could you do something like:
if(array.Element[0] != null || array.Element[1] != null){
//execute code
}

Your code is probably subject to refactor.
I assume it can work this way:
var obj = array.Element.FirstOrDefault(x => x.Object.Length > 0);
if (obj != null)
{
if (obj.Object[0].Item.Length != 0)
{
// do whatever is necessary
}
}

I think you can put your check in right before your first if Check.
if (array.Length > 1 && array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
This should just short-circuit out if your array doesn't have both Elements.

Place both tests together using the short-circuit && so that the second test doesn't occur if the first fails:
object element0 = array.Element[0].Object;
object element1 = array.Element[1].Object;
// Ensure at least one Object array has a non-empty value.
if ((element0.Length > 0 && !string.IsNullOrEmpty((string)element0.Object[0].Item))
|| (element1.Length > 0 && !string.IsNullOrEmpty((string)element1.Object[1].Item)))
{
// ...
}
I am presuming it is Object[1] causing the exception--you weren't clear on that. If it is Element[1] that causes the exception (or both), then you need to pre-test the length of the array:
if ((array.Element[0].Length != 0 && HasValue(array.Element[0].Object))
|| (array.Element[1].Length > 1 && HasValue(array.Element[1].Object)))
{
// ...
}
// <summary>
// Returns true if the specified string array contains a non-empty value at
// the specified index.
// </summary>
private bool HasValue(System.Array array, int index)
{
return array.Length > index &&
!string.IsNullOrEmpty((string)array.Object[index].Item);
}

for (long i = 0; i <= (output3.Length); i++)
{
output1.WriteByte(output3[i]); -----> index out of range exception correct it
output1.WriteByte(output3rx[i]);
}

Related

ASP.NET/Entity : Issue with my Array Index

I have managed to pull out the FirstorDefault() in the Query, however, some of these address types in the database actually have more than 1 address: therefore, I am trying to build an array of every address regarding each one.
The current code:
int counter = 0;
string queryID = "";
List<string> busAddr = new List<string>();
while (counter != busIDs.Count)
{
queryID = busIDs[counter];
var gathered = (from c in db.tblbus_address where c.BusinessID == queryID && c.AddressTypeID == addrnum select c).ToArray();
int gath = 0;
if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
{
var address = gathered[gath] as tblbus_address;
string test = "";
while (gath != address.Address1.Length)
{
var all = address.Address1;
test += address.Address1.ToString() + ",";
}
busAddr.Add(test);
}
else
{
busAddr.Add("No address for this type exists...");
}
counter++;
gath++;
}
I am receiving an error:
Index was outside the bounds of the array.
at this line:
if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
Can anyone point me in the right direction? I know this structure is the issue but I cannot think how to approach the situation.
You are trying to get the element gathered[gath] when there are no items in gathered. Adding a check for null and Any will help you
if(gathered!=null && gathered.Any()
&& (gathered[gath] as tblbus_address) != null
&& !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
{
...
...
}

How to check if there is an element at the specific index in a list?

How to check if there is an element at the specific index in a list, like
Product[i]
Is it there or not? How to write this check?
If i is the index you want to have, check the Count:
if (i >= 0 && (list.Count - 1) >= i)
{
// okay, the item is there
}
If talking about nullable types, you could also check if the item on that index isn't null:
if (i >= 0 && (list.Count - 1) >= i && list[i] != null)
{
// okay, the item is there, and it has a value
}
try like this
if (Product.Contains(yourItem))
int Index = Array.IndexOf(Product, yourItem);
if you want to check that the index is exist in that particular array then you can just check the length of that array.
if (i < Product.Length && i > -1)
//yes it has
return (Product.Count() -1) <= i;
or if you're feeling hackish:
try { var x = Product[i]; return true; } catch(ArrayIndexOutOfBoundException) { return false; }
or
Product.Skip(i).Any()
or...

Convert String To Int in LINQ

I have a LINQ query that queries a DataTable. In the DataTable, the field is a string and I need to compare that to an integer, basically:
if ((electrical >= 100 && electrical <= 135) || electrical == 19)
{
// The device passes
}
the problem is, I am trying to do this in LINQ like this:
var eGoodCountQuery =
from row in singulationOne.Table.AsEnumerable()
where (Int32.Parse(row.Field<String>("electrical")) >= 100 &&
Int32.Parse(row.Field<String>("electrical")) <= 135) &&
Int32.Parse(row.Field<String>("electrical")) != 19 &&
row.Field<String>("print") == printName
select row;
I keep getting the exception:
Input string was not in a correct format
The main problem occurs when electrical == ""
Unfortunately, the framework doesn't provide a nice clean way to handle parsing scenarios where it fails. Of what's provided, they only throw exceptions or use out parameters, both of which does not work well with linq queries. If any one value you're parsing fails, the entire query fails and you just can't really use out parameters. You need to provide a method to handle the parsing without that does not throw and does not require using out parameters.
You can handle this in many ways. Implement it where upon failure, you return some default sentinel value.
public static int ParseInt32(string str, int defaultValue = 0)
{
int result;
return Int32.TryParse(str, out result) ? result : defaultValue;
}
Or what I would recommend, return a nullable value (null indicating it failed).
public static int? ParseInt32(string str)
{
int result;
return Int32.TryParse(str, out result) ? result : null;
}
This simplifies your query dramatically while still leaving it readable.
public bool GetElectricalStatus(string printName)
{
var query =
from row in singulationOne.Table.AsEnumerable()
where row.Field<string>("print") == printName
// using the nullable implementation
let electrical = ParseInt32(row.Field<string>("electrical"))
where electrical != null
where electrical == 19 || electrical >= 100 && electrical <= 135
select row;
return !query.Any();
}
p.s., your use of the Convert.ToInt32() method is incorrect. It is the same as calling Int32.Parse() and does not return a nullable, it will throw on failure.
I would check if the data in the column does not contain leading/trailing whitespaces - i.e. "15 " rather than "15" and if it does (or might do) trim it before trying to convert:
Int32.Parse(row.Field<String>("electrical").Trim())
BTW: not related to the error but I'd use let statement to introduce a local variable and do the conversion once:
let x = Int32.Parse(row.Field<String>("electrical").Trim())
where x >= 100...
I could not get anything to work, so I re-did the whole method:
public bool GetElectricalStatus(string printName)
{
List<object> eGoodList = new List<object>();
var eGoodCountQuery =
from row in singulationOne.Table.AsEnumerable()
where row.Field<String>("print") == printName
select row.Field<String>("electrical");
foreach (var eCode in eGoodCountQuery)
{
if (!string.IsNullOrEmpty(eCode.ToString()))
{
int? eCodeInt = Convert.ToInt32(eCode);
if (eCodeInt != null &&
(eCodeInt >= 100 && eCodeInt <= 135) || eCodeInt == 19)
{
eGoodList.Add(eCode);
}
}
}
if (eGoodList.Count() > 0)
{
return false;
}
else
{
return true;
}
}
The main problem occurs when electrical == ""
Why not make a function that does your evaluation, and call it in your Linq query. Put logic in to check the validity of the data contained within (so if you can't parse the data, it should return false)...
The function:
bool IsInRange(string text, int lower, int upper, params int[] diqualifiers)
{
int value = int.MinValue;
if (!int.TryParse(text, out value)) {
return false;
}
if (!(value >= lower && value <= upper)) {
return false;
}
if (disqualifiers != null && disqualifiers.Any(d => d == value)) {
return false;
}
return true;
}
The Linq query...
var eGoodCountQuery =
from row in singulationOne.Table.AsEnumerable()
where
IsInRange(row.Field<String>("electrical"), 100, 135, 19)
&& row.Field<String>("print") == printName
select row;

Checking for null property

I want to check that a property on an array which is itself a child object is not null.
So i have
if (Parent.Child != null && Parent.Child[0] != null && Parent.Child[0].name != null)
var myName = Parent.Child[0].name
This seems like a very long winded way to get to the child[0].name whilst avoiding null reference exceptions. I am also getting index out of range errors. Is there a better way?
If you're getting IndexOutOfRangeException errors, that suggests that Parent.Child could be empty. So really you want:
if (Parent.Child != null && Parent.Child.Count > 0 && Parent.Child[0] != null &&
Parent.Child[0].name != null)
{
...
}
There's nothing that would simplify this very much, although you could write a version of LINQ's FirstOrDefault method which even coped with the source being null:
public static T NullSafeFirstOrDefault(this IEnumerable<T> source)
{
return source == null ? default(T) : source.FirstOrDefault();
}
Then:
var firstChild = Parent.Child.NullSafeFirstOrDefault();
if (firstChild != null && firstChild.name != null)
{
...
}
Your code appears OK apart from missing a test for the array being empty and is the correct defensive programming. You should extract this into a method to make it's intention clearer and your code here cleaner:
if (Parent.HasChild())
{
var myName = Parent.Child[0].name;
}
public bool HasChild()
{
return this.Child != null && this.Child.Count > 0 &&
this.Child[0] != null && this.Child[0].name != null;
}
The only other way would be to wrap the code in a try/catch block:
try
{
var myName = Parent.Child[0].name;
...
}
catch
{
}
However, this is bad programming practice as:
You are using exceptions to control program flow.
You are hiding other potentially serious errors.
try
var Names = new List<string>();
if(Parent.Child != null && Parent.Child.Count() > 0){
foreach(var item in Parent.Child) Names.Add(item.name)
}
var ParentChild= Parent.Child[0] ;
if (Parent.Child != null && ParentChild != null &&ParentChild.name != null)
var myName = ParentChild.name
Maybe simple try/catch will help?
var myName;
try
{
myName = Parent.Child[0].name;
}
catch (NullReferenceException)
{ myName = null; }

DataTable.Select() Property: Giving Index Out of Bound Exception

I'm trying to select only those rows which have Parent ID = 0
int predecessor = Parent;
StringBuilder valuePath = new StringBuilder();
valuePath.Append(Parent.ToString());
DataRow[] drPar;
while (true)
{
drPar = dt.Select("MenuID=" + predecessor);
if (drPar != null)
{
if (drPar[0]["ParentID"].ToString().Equals("0"))
break;
}
drPar[0]["ParentID"].ToString().Equals("0") is giving me
Out of Bound exception ..
Help Please !
DataTable.Select does not return null when there's no matching DataRow but an array with Length==0.
But apart from that, why are you using an "infinite" loop for only one statement?
So this should work:
drPar = dt.Select("MenuID=" + predecessor);
if (drPar.Length != 0)
{
if (drPar[0]["ParentID"].ToString().Equals("0"))
{
// ...
}
}
The array drPar must be empty to give this error as it is the only index you use in your code.
Try
if (drPar != null && drPar.Length > 0)

Categories

Resources