Jagged Array for storing passwords

I come from Java, and I love two-dimensional arrays. I looked it up in C# and here they’re called Jagged Arrays - they seem perfect for the purpose of our multi-level password options. Here’s my code:

Then you can easily set any password from any list, using a single line, without using if/switch logic:

2 Likes

Great solution! I did something very similar :slight_smile:

You could simplify your password instantiation a little as follows:

passwordList = new string[][]
{
     new string[] { "book", "clown", "level", "jump", "seven" },
     new string[] { "desktop", "velvet", "cupboard", "notepad", "painting" },
     new string[] { "refrigerator", "upstanding", "degeneracy", "quarantine", "lumberjack" },
};

Not a major change, but cleans up the code a little bit!

2 Likes

Ooh, I love that syntax! Thanks for showing me, i’ll add it to my code!

1 Like

This is nearly identical to what I did, though I used a slightly different array format.

    string[,] passwords = new string[,] {
        { "locker", "notebook","chalk" },
        {"badge", "warrant", "hoover" },
        {"backplane", "memory","matrix" }
    };

I don’t think it’s as readable as what you did as I find the [,] formatting a little strange coming from a C++ and Java background, but it’s clean and simple.

These are fixed dimension arrays though, not a “jagged” array where each “row” contains a varying number of “column” elements.

So this form may be exactly what you wanted/needed, but it is (strictly speaking) serving a different goal.

C# always offers a few variations of the same declaration though, as its grown in syntactic sugars over the years, yet retains pretty much all of the original syntaxes too.

Another example on the jagged front with some slight alterations, given I don’t have to declare the types or quantity of dimensions up front:

var multiDimStrings = new[] {
	new[] {"Oh", "the", "grand", "old", "Duke", "of", "York"},							   
	new[] {"he", "had", "ten", "thousand", "men"},
	new[] {"he", "marched", "them", "up", "to", "the", "top", "of", "the", "hill"},
	new[] {"and", "now", "I'm", "tired", "of", "writing", "this", "all", "out"}
};

foreach(var line in multiDimStrings) {
	foreach(var word in line) {
		Console.Write(word + " ");
	}
	Console.WriteLine();
}

Console.WriteLine(multiDimStrings.GetType());
Console.WriteLine(multiDimStrings[1][3]);

Result:

Oh the grand old Duke of York 
he had ten thousand men 
he marched them up to the top of the hill 
and now I'm tired of writing this all out 
System.String[][]
thousand

Try it: https://dotnetfiddle.net/cycZVD

This is fantastic, topdog. Jagged arrays are wonderful. I changed my code to use them instead and now I can use .Length to determine the length of each sub array on the fly. So much easier and also easier to read.

Thank you!

Privacy & Terms