c#


C# IndexOutOfRange Array Exception


I'm trying to create a 2D char array to hold a grid of chars which will be used as a sort of 'map' for a 2D console game.
I am getting a:
IndexOutOfRange exception
..and cannot see why. I've stepped through the code in debug mode and still cannot see the issue.
It steps through the code fine until it hits X = 25 and Y = 1, the upper right boundary of my grid.
I have _gameWidth and _gameHeight created as follows, outside of main but still inside the class:
static int _gameWidth = 25;
static int _gameHeight = 15;
Following is the code that fails, when trying to generate and populate the grid. It fails at this point:
else if (x == _gameWidth && y == 1)
_grid[x, y] = '╕';
static void GenerateGrid()
{
for (int y = 1; y <= _gameHeight; y++)
{
for (int x = 1; x <= _gameWidth; x++)
{
if (x == 1 && y == 1)
_grid[x, y] = '╒';
else if (x == _gameWidth && y == _gameHeight)
_grid[x, y] = '╛';
else if (x == _gameWidth && y == 1)
_grid[x, y] = '╕';
else if (x == 1 && y == _gameHeight)
_grid[x, y] = '╘';
else if ((x != 1 && y == _gameHeight) || (x != _gameWidth && y == 1))
_grid[x, y] = '═';
else if ((x == 1 && y > 1 && y < _gameHeight) || (x == _gameWidth && y > 1 && y < _gameHeight))
_grid[x, y] = '│';
else
_grid[x, y] = 'x';
}
Console.WriteLine("");
}
}
This exception means that you have accessed an invalid index. From the way you have written the loop I can tell that you think that indexes go from 1 to the length of the array. Arrays are zero-based, though. Use the standard loop form:
for (int i = 0; i < length; i++)
Your loop starts at one. You can use the Visual Studio for loop template. Just type "for<tab><tab>".
Your program might benefit from the Code Review Stack Exchange site.
Change
for (int i = 1; i <= gameHeight; i++)
to
for (int i = 0; i < gameHeight; i++)
and do the same for width.
EDIT:
This is because array indexes start at the number 0 and end with the length of the array minus 1.

Related Links

Unable to connect to SQL Server 2012 in a LAN
Best retry policy for Refit ApiException?
Avoid skipping elements in xml reader
Deserialize JSON response with unknown object names using c# ReadObject()
How to compile asp.net website project as case sensitive?
Mapping to 2 or more projects with common source
axWindowsMediaPlayer - black screen when video in playlist changes
Null Context.User
How to pass array value in oracledynamicparameter
get html table in c# with htmlagilitypack
Why using '#' character when use XML (System.Xml) [closed]
Visual Studio: Launch exe from (nuget) dependency
Access to the path 'C:\ProgramData\Application Data' is denied
Entity Framework, Order Manager class
Microsoft Graph - Get MemberOf
Changing Label Text line depending on Length in C#

Categories

HOME
grizzly
redux
wifi
skypedeveloper
azure-database-mysql
magento-1.9.2.1
arguments
app-store
sms
aggregate-functions
rtc
subprocess
runtime
tracking
console-application
appsettings
internet-explorer-7
jq
connectiq
klipfolio
mattermost
prepros
oracle-golden-gate
pumping-lemma
expressionengine
mongoose-im
android-6.0-marshmallow
proof-general
large-files
dynamic-memory-allocation
angular-schema-form
2checkout
xlib
andengine
mplab
restler
apache-falcon
powerbi-embedded
aweber
leaderboard
strategy-pattern
stochastic-process
gem-fury
julia-jump
mtm
apiman
logan-square
yank
django-tables2
ng-class
px4
gige-sdk
activesupport
typewriter
sqlproj
copy-constructor
mac-app-store
jira-agile
django-taggit
mod
ideavim
music-player
opendolphin
jts
transport
personality-insights
jain-sip
winforms-interop
tooltwist
photogrammetry
perfect-scrollbar
random-access
uiblureffect
conditional-comments
rails-migrations
pyalgotrade
enquire.js
object-oriented-database
infor-eam
complete
infomaker
infinity.js
azure-scheduler
bho
spawn
cloudmade
architectural-patterns
boost.build
nsregularexpression
certificate-revocation
dancer
helicontech
facebook-winjs-sdk
rjs
recess
html5-animation
conditional-operator
xcdatamodel
google-local-search
qprocess
numerical-computing
coderush-xpress
authkit
opengl-to-opengles
ffdshow

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App