filling an array in a struct c# - c#

I'm trying to fill an array that is contained within a structure with some values but I keep getting errors no matter what I try.
my structure looks like this
public struct boardState
{
public int structid;
public char[] state;
}
bellow in the initializer I'm creating a new boardState and trying to fill it with some values like this
boardState _state_ = new boardState();
_state_.structid = 1;
_state_.state[9] = {'o','-','-','-','o','-','-','-','-','o'};
structid seems to work fine, but I get an error at the {'o','-' etc etc} telling me '; expected'. I've been through the code above and ensured that there are no ;'s missing (confirmed by the program running without this line) so I'm guessing you can't assign to the array in this way. How can I assign to the state array?
EDIT: - added the comma that I'd missed but still getting the same error.

You don't need [9]. It tries to assign an array to a single char. Instead just use this:
_state_.state = new char [] {'o','-','-','-','o','-','-','-','-','o'};

You're missing a comma and the syntax is off.
From:
_state_.state[9] = {'o','-','-','-','o','-','-','-','-''o'};
To:
_state_.state = new char [] {'o','-','-','-','o','-','-','-','-','o'};

Related

Setting array items from a custom created class

In Xamarin I have the following class that I have created:
class MapLocation
{
public LatLng Location;
public BitmapDescriptor icon;
public String Snippet;
public String Title;
}
I am trying to add MapLocation elements to this array as follows:
private MapLocation[] MapLocations = new MapLocation[1];
MapLocations[0].Location = new LatLng(-45.227660, 174.212731);
MapLocations[0].Title = 'Test Title';
MapLocations[1].Location = new LatLng(-45.227834, 174.212857);
MapLocations[1].Title = 'Test Title';
I am normally a Visual Basic programmer, and I am not sure as to what is wrong with the above code.
May I have some help to get this code working?
Thanks in advance.
In C# new takes as parameter size (length) of array, not the last index (which is length-1). So just change it to
new MapLocation[2];
At first sight, the only wrong I see is that you have defined an array of one item new MapLocation[1], and you're accessing two items (0 and 1)
Looking into above code it seems that you have created array with length = 1. and you are adding two elements into it. This might be the case which causing the problem.
Change the initialization statement like this :
private MapLocation[] MapLocations = new MapLocation[2];

Can I GET and SET an array in C#?

HOMEWORK QUESTION:
I need to create a simple trivia game that reads from a CSV file. My data for a particular question is structured as follows: "Question;AnswerA;AnswerB;AnswerC;AnswerD;CorrectAnswerLetter".
We're using a series of getters and setters to hold all the relevant data for a single question object, and I'm running into a problem with the array I've created to hold the four answers.
In my constructor, I'm using this code--which I believe instantiates the Answer array in question:
class TriviaQuestionUnit
{
...
const int NUM_ANSWERS = 4;
string[] m_Answers = new String[NUM_ANSWERS];
public string[] Answer
{
get { return m_Answers[]; }
set { m_Answers = value[];
}
...
// Answer array
public string[] GETAnswer(int index)
{
return m_Questions[index].Answer;
}
...
}
I'm accessing the getter and setter from my TriviaQuestionBank method, which includes this code:
...
const int NUM_QUESTIONS = 15;
TriviaQuestionUnit[] m_Questions = new TriviaQuestionUnit[NUM_QUESTIONS];
...
// Answer array
public string[] GETAnswer(int index)
{
return m_Questions[index].Answer;
}
...
I'm using using StreamReader to read a line of input from my file
...
char delim = ';';
String[] inputValues = inputText.Split(delim);
...
parses the input in an array from which I create the question data. For my four answers, index 1 through 4 in the inputValues array, I populate this question's array with four answers.
...
for (int i = 0; i < NUM_ANSWERS; i++)
{
m_Questions[questionCounter].Answer[i] = inputValues[i + 1];
}
...
I'm getting errors of Syntax code, value expected on the getters/setters in my constructor, and if I change the variable to m_Answers[NUM_QUESTIONS] I get an error that I can't implicitly convert string to String[].
Hopefully I've posted enough code for someone to help point me in the right direction. I feel like I'm missing something obvious, but I just cannot make this work.
Your code has some errors that will cause compilation errors, so my first lesson for you is going to be: listen to the compiler. Some of the errors might seem a bit hard to understand sometimes, but I can ensure you that a lot of other people have had the same problems before; googling a compiler error often gives you examples from other people that are similar to your issue.
You say "In my constructor", but the problem is that your code does not have a constructor. You do however initialize fields and properties on your class and surely enough, the compiler will create a default constructor for you, but you have not defined one yourself. I am not saying that your code does not work because you do not have a constructor, but you might be using the wrong terms.
The first problem is in your first code snippet inside TriviaQuestionUnit. Your first two lines are working correctly, you are creating a constant integer with the value 4 that you use to determine how large your array is going to be and then you initialize the array with that given number.
When you do new string[NUM_ANSWERS] this will create an array, with default (empty) values.
The first problem that arises in your code is the getters and setters. The property expects you to return an array of strings which the method signature in fact is telling us:
public string[] Answer
However, looking at the getter and setter, what is it that you return?
m_Answers is a "reference" to your array, hence that whenever you write m_Answers you are referring to that array. So what happens when we add the square brackets?
Adding [] after the variable name of an array indicates that we want to retrieve a value from within the array. This is called the indexer, we supply it with an index of where we want to retrieve the value from within the array (first value starts at index 0). However, you don't supply it with a value? So what is returned?
Listen to the compiler!
Indexer has 1 parameter(s) but is invoked with (0) argument(s)
What does this tell you? It tells you that it doesn't expect the empty [] but it would expect you to supply the indexer with a number, for instance 0 like this: [0]. The problem with doing that here though, is that this would be a miss-match to the method signature.
So what is it that we want?
We simply want to return the array that we created, so just remove [] and return m_Answers directly like this:
public string[] Answer
{
get { return m_Answers; }
set { m_Answers = value; }
}
Note that you were also missing a curly bracket at the end if the set.
When fixing this, there might be more issues in your code, but trust the compiler and try to listen to it!

How to access individual fields within struct array

I'm trying to complete an assignment and I'm having trouble with the following (I have worked on this for the last 12 hours). Please help.
I have opened a file, saved the file into an struct array. Can access each element of the struct but don't know how I can access each individual field. i.e
Struct
//struct to hold the hand values
public struct CurrentHand
{
public char cardSuit;
public int cardValue;
}
I need to extract the cardValue into an array or variables so I can evaluate each record i.e. is the hand a pair or two pair etc. I have no idea how to do this. From what I have found its not possible to access each field, is this true?
//Open file and load data into array
public static void LoadHandData(CurrentHand[] handData, string fileName)
{
string input = ""; //temporary variable to hold one line of data
string[] cardData; //temporary array to hold data split from input
//Open the file and read the contents
StreamReader readHand = new StreamReader(fileName);
input = readHand.ReadLine(); //one record
cardData = input.Split(' '); //split record into fields
for (int counter = 0; counter < handData.Length; counter++)
{
handData[counter].cardSuit = Convert.ToChar(cardData[counter *2]);
handData[counter].cardValue = Convert.ToInt16(cardData[counter *2 +1]);
}
readHand.Close();
}
To obtain an array containing the values of the cards you hold in your hand, you can do:
var values = handData.Select(x=>x.cardValue).ToArray();
var seeds = handData.Select(x=>x.cardSuit).ToArray();
By the way, your struct should be called Card or something like that, since an Hand is supposed to be a collection of cards. The name you gave to it is just confusing and makes your code less readeable.
Your problem is not clear to me. anyway you can access invidual fields using .
try this...
CurrentHand.cardValue
using above you can get and set value for CurrentHand structure.

C# Using a struct

I am using Mono Develop For Android and would like some help with using an array of structs.
Here is my code:
public struct overlayItem
{
string stringTestString;
float floatLongitude;
float floatLatitude;
}
And when using this struct:
overlayItem[1] items;
items[0].stringTestString = "test";
items[0].floatLongitude = 174.813213f;
items[0].floatLatitude = -41.228162f;
items[1].stringTestString = "test1";
items[1].floatLongitude = 170.813213f;
items[1].floatLatitude = -45.228162f;
I am getting the following error at the line:
overlayItem[1] items;
Unexpected symbol 'items'
Can I please have some help to correctly create an array of the above struct and then populate it with data.
Thanks
Define your struct like:
overlayItem[] items = new overlayItem[2];
Also you need to define your fields in the struct as public, to be able to access them outside the struct
public struct overlayItem
{
public string stringTestString;
public float floatLongitude;
public float floatLatitude;
}
(you may use Pascal case for your structure name)
You need to create your struct array like so:
overlayItem[] items = new overlayItem[2];
Remember to declare it with [2] as it will have 2 elements, not 1! Indexing an array might start at zero, but defining an array size does not.
Your sample code shows you need two items, so you need to declare the array of structs with length 2. This can be done with:
overlayItem[] items = new overlayItem[2];
The right way to declare the struct array for two elements is
overlayItem[] items = new overlayItem[2];
If you do not know the exact no of items you can also use list.
List<overlayItem> items = new List<overlayItem>();
items.Add( new overlayItem {
stringTestString = "test";
floatLongitude = 174.813213f;
floatLatitude = -41.228162f;
}
);

2-dimensional arrays in C# and how to return the array

I'm having trouble with declaring 2-dimensional arrays in C#, populating them and then returning the array.
At the moment, I'm declaring the array like so:
private static string[,] _programData = new String[50,50];
public string[,] ProgramData
{
get
{
return _programData;
}
}
_programData is showing the error 'cannot implicitly convert from type 'string[,] to string[][]'
I should point out that I am attempting to call ProgramData from another class like so:
for (serviceCount = 0; serviceCount <= ffm.Program.Length; serviceCount++)
{
Console.WriteLine("Program Number: " + ffm.Program[serviceCount].ToString());
for (serviceDataCount = 0; serviceDataCount <= ffm.ProgramData.Length; serviceDataCount++)
{
**Console.WriteLine("\t" + ffm.ProgramData[serviceCount, serviceDataCount].ToString());**
}
}
Error occurs on the bold line above with:
Object reference not set to an instance of an object.
I don't think there seems to be an issue with how I've declared the array, its just the type mismatch that I don't understand.
Regards
Firstly, calling ffm.ProgramData.Length will return 2500 (50 * 50) as stated above, so you need to fix that count to ffmProgramData.GetLength(1) to return the size of the second dimension.
Secondly, the error you get "Object reference not set to an instance of an object" occurs because you're referencing an uninitialized part of the array. Ensure that the array is filled, or at the very minimum, full of empty strings (obviously you need to run this loop in the constructor changing the variable names where appropriate, because ProgramData is read only as you have it):
for(int fDim = 0; fDim < ffm.ProgramData.GetLength(0); fDim++)
for(int sDim = 0; sDim < ffm.ProgramData.GetLength(1); sDim++)
ffm.ProgramData[fDim, sDim] = "";
Thirdly, you don't need to call the ToString() method inside the loop. You're casting a string to a string.
programData is showing the error
'cannot implicitly convert from type
'string[,*] to string[][]'
No, it does not show any error. The code compiles just fine (with C# 3.5).

Categories

Resources