Reputation: 237
I have created an array like this
string[] directories = new string[15];
And then I want to do something with it like so
for (int i = 0; i < directories.Length; i++) {
//code
}
The user can input as many directories in the array as they want, but if they don't put 14 elements in it, the rest of the array is obviously going to be NULL and the for loop doesn't stop untill it reaches the 14th element. How can I make the loop stop at the last directory in the array and not count the NULL?
I've tried this but it returns the following error: System.NullReferenceException: 'Object reference not set to an instance of an object.'
for (int i = 0; i < directories .Length; i++) {
//code
string directory = directories[i];
if (directory.Equals(null)){
return;
}
// more code
}
Thank you and sorry for the lack of experience and bad English.
Upvotes: 1
Views: 1857
Reputation: 404
Use a List <string>
instead of string[]
:
string strDir = "./";
List<string> directories = new List<string>();
directories.Add(strDir);
for (int i = 0; i < directories.Length; i++) {
//code
}
edit: Of course a null-check can be implemented, however in my opinion it is not necessary due to
The user can input as many directories in the array as they want
Upvotes: -1
Reputation: 3161
If you can skip index you can use Linq's Where:
foreach (var dir in directories.Where(x => x != null)
{
}
If you need index of items:
for (int i = 0; i < directories.Length; i++)
{
string directory = directories[i];
if (directory == null)
{
return; // Note that rest of items will be ignored. method will end code outside for loop will not be executed
//break; // exit loop on first null. code outside for loop will be executed
//continue; // use continue to skip null item and process rest of items. code outside for loop will be executed
}
// more code
}
Upvotes: 0
Reputation: 1029
Try:.
directories.Count(x => x != null):
If you can always guarantee that after the first null, everything else is null, then the following will work to replace the if statement in your code, and be more efficient than the linq above:
if (directory == null)
break;
The break keywords prevents any more looping in c#.
If you really want to have a set of values in an array followed by a set of nulls, have you considered using a list rather than an array?
Upvotes: 6
Reputation: 1618
A quick and easy way to check for directories (if they are directories and the strings aren't null
) would be something like this, using Linq:
namespace FooApp {
using System.IO;
using System.Linq;
class MyFoo {
public static void Main(string[] args) {
foreach (var dir in args.Where(a => !string.IsNullOrEmpty(a) && Directory.Exists(a))) {
// Valid directory. Do as you please
}
}
}
}
EDIT: If you don't want to check if a directory is valid and just want to check if the string is non-null,you can leave Directory.Exists() out.
Upvotes: 0
Reputation: 20354
If directory
is null, you won't be able to call Equals()
.
Just try directory == null
Upvotes: 2