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;
}
);
Related
Suppose I have a class like this:
class Array{
int[] values;
}
Now suppose I have a class that stores a lot of Arrays:
class ArrayOfArrays{
Array[] arrays;
}
Suppose, for some reason, I want to get the last Array of arrays and put in a variable (for better readability). In C, I would do like Array last = &ArrayOfArraysObject.arrays[lastIndex]. As I won't modify it, for better performance, I don't need to copy the whole array, just a reference do the job.
Can I have this kind of behaviour in C# ? (without using function calls, I don't want to create a function just to use the keyword ref, it looks like overkill)
You could create a public property that returns the last element of arrays.
class ArrayOfArrays
{
Array[] arrays;
public Array LastOfArrays { get { return arrays.Last(); } }
}
Test it:
var aoa = new ArrayOfArrays();
// Initialize and enter data here
//When you want to use the last item:
var last = aoa.LastOfArrays;
last.values[0] = 333;
Now, aoa.arrays[LastElement].values[0] would also be 333. So you essentially do keep the reference here, and does not copy the entire array.
Confirmation:
Arrays already use references in C#. You don't have to do anything special, and you get the behavior you want:
int[][] foo = new int[][] { new int[] {1,2,3}, new int[]{4,5,6}, new int[]{7,8,9} };
var bar = foo[2];
foo[2][2] = 0; // make a change **after** assigning to bar
Console.WriteLine(bar[2]); // outputs "0" -- bar knows about the change
bar[1] = 6; // same thing, but in reverse
Console.WriteLine(foo[2][1]); // outputs "6" -- foo knows about the change
In the example above, foo[2] and bar are references to the same array in memory. bar was not just a copy.
I am looking for a way to access an array item in an array, which is held by another array. I can't quite figure it out :/
I have 2 scripts: Game_Manager.cs and Board.cs.
In Board.cs I have the following variables. (The array size adjusts automatically on start):
public Transform[] Clubs_Bottom = new Transform[0];
public Transform[] Clubs_Top = new Transform[0];
public Transform[] Spades_Left = new Transform[0];
public Transform[] Spades_Right = new Transform[0];
public Transform[] Diamonds_Left = new Transform[0];
public Transform[] Diamonds_Right = new Transform[0];
public Transform[] Hearts_Bottom = new Transform[0];
public Transform[] Hearts_Top = new Transform[0];
In Game_Manager.cs I have the following method:
public void setCardBoardSlot(int Hand_CardNumber)
{
Array[] ArrayList = new Array[8]; // The card arrays
// Fill our array list
ArrayList[0] = Board.Script.Diamonds_Left;
ArrayList[1] = Board.Script.Diamonds_Right;
ArrayList[2] = Board.Script.Clubs_Top;
ArrayList[3] = Board.Script.Clubs_Bottom;
ArrayList[4] = Board.Script.Spades_Left;
ArrayList[5] = Board.Script.Spades_Right;
ArrayList[6] = Board.Script.Hearts_Bottom;
ArrayList[7] = Board.Script.Hearts_Top;
// Acces Array item 1's array, and the first item in that array
ArrayList[0[0]].GetComponent<SpriteRenderer().sprite=SpriteManager.Script.setActive();
}
This method is just demonstrative until i find out how to access each array item. I get the following error on the 2nd to last line when I use this code:
Cannot apply indexing with [] to an expression of type 'int'
The Array class essentially contains a generic array - so an array of Array can contain arrays of different types (which may change at runtime). Accesing an element of that array returns a single instance of class Array (not the array itself) so using ArrayList[0][0] would result in a compiler error "Cannot apply indexing with [] to an expression of type 'Array'".
Using an array of class Array you would need to explicitly cast the array element to your array type (which is an array of Transform) & then access the first element in this way :
((Transform[])ArrayList[0])[0].GetComponent<SpriteRenderer().sprite=SpriteManager.Script.setActive();
As all of your contained arrays are of the same type - a simpler way would be to use an array of array of Transform - your declaration of ArrayList would become :
Transform[][] ArrayList = new Transform[8][];
the assignments to each array element would be unchanged and then you could simply use:
ArrayList[0][0].GetComponent<SpriteRenderer().sprite=SpriteManager.Script.setActive();
Note that ArrayList is a defined class type in C# - although the compiler can determine by context that you are referring to the variable, in my opinion, it is better to avoid using .Net class names as variable names.
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];
I have a struct in C# and I define and array list of my struct based on my code that I express here. I add items in my array list, but I need to delete a few rows from my list too. Could you help me how can I delete item or items from my struct array list:
public struct SwitchList
{
public int m_Value1, m_Value2;
public int mValue1
{
get { return m_Value1; }
set {m_Value1 = value; }
}
public int mValue2
{
get { return m_Value2; }
set {m_Value2 = value; }
}
}
//Define an array list of struct
SwitchList[] mSwitch = new SwitchList[10];
mSwitch[0].mValue1=1;
mSwitch[0].mValue2=2;
mSwitch[1].mValue1=3;
mSwitch[1].mValue2=4;
mSwitch[2].mValue1=5;
mSwitch[2].mValue2=6;
Now how can I delete one of my items, for example item 1.
Thank you.
Arrays are fixed length data structures.
You will need to create a new array, sized one less than the original and copy all items to it except the one you want to delete and start using the new array instead of the original.
Why not use a List<T> instead? It is a dynamic structure that lets you add and remove items.
You will need to move elements around and resize the array (which is expensive), since there is some complexity there you going to want to hide it in class that just presents the collection without exposing the implementation details of how its stored. Fortunately Microsoft has already provided a class that does just this called List<T> which along with a few other collection types in System.Collections.Generic namespace meet most common collection needs.
as a side note, you should use auto-properties instead of the trivial property style that you ha
That's not possible, because an array is a fixed size block of elements. Because structs are values types and not reference types, you also can't just set the element zo null. One option would be to create a new smaller array and to copy your remaining values to the new array. But the better approach would be to use a List in my opinion.
If you really, really want to use arrays and move things around, here are some examples of how to do it:
{
// Remove first element from mSwitch using a for loop.
var newSwitch = new SwitchList[mSwitch.Length - 1];
for (int i = 1; i < mSwitch.Length; i++)
newSwitch[i - 1] = mSwitch[i];
mSwitch = newSwitch;
}
{
// Remove first element from mSwitch using Array.Copy.
var newSwitch = new SwitchList[mSwitch.Length - 1];
Array.Copy(mSwitch, 1, newSwitch, 0, mSwitch.Length - 1);
mSwitch = newSwitch;
}
my problem is as follows:
Im building a console application which asks the user for the numbers of objects it should create and 4 variables that have to be assigned for every object.
The new objects name should contain a counting number starting from 1.
How would you solve this?
Im thinking about a class but im unsure about how to create the objects in runtime from userinput. Is a loop the best way to go?
What kind of class, struct, list, array .... would you recommend. The variables in the object are always the same type but i need to name them properly so I can effectivly write methods to perform operations on them in a later phase of the program.
Im just learning the language and I would be very thankful for a advice on how to approach my problem.
If I understand your problem correctly:
class MyClass
{
public int ObjectNumber { get; set; }
public string SomeVariable { get; set; }
public string AnotherVariable { get; set; }
}
// You should use keyboard input value for this
int objectsToCreate = 10;
// Create an array to hold all your objects
MyClass[] myObjects = new MyClass[objectsToCreate];
for (int i = 0; i < objectsToCreate; i++)
{
// Instantiate a new object, set it's number and
// some other properties
myObjects[i] = new MyClass()
{
ObjectNumber = i + 1,
SomeVariable = "SomeValue",
AnotherVariable = "AnotherValue"
};
}
This doesn't quite do what you described. Add in keyboard input and stuff :) Most of this code needs to be in some kind of Main method to actually run, etc.
In this case, I've chosen a class to hold your 4 variables. I have only implemented 3 though, and I've implemented them as properties, rather than fields. I'm not sure this is necessary for your assignment, but it is generally a good habit to not have publically accessible fields, and I don't want to be the one to teach you bad habits. See auto-implemented properties.
You mentioned a struct, which would be an option as well, depending on what you want to store in it. Generally though, a class would be a safer bet.
A loop would indeed be the way to go to initialize your objects. In this case, a for loop is most practical. It starts counting at 0, because we're putting the objects in an array, and array indexes in C# always start at 0. This means you have to use i + 1 to assign to the object number, or the objects would be numbered 0 - 9, just like their indexes in the array.
I'm initializing the objects using object initializer syntax, which is new in C# 3.0.
The old fashioned way would be to assign them one by one:
myObjects[i] = new MyClass();
myObjects[i].ObjectNumber = i + 1;
myObjects[i].SomeVariable = "SomeValue";
Alternatively, you could define a constructor for MyClass that takes 3 parameters.
One last thing: some people here posted answers which use a generic List (List<MyClass>) instead of an array. This will work fine, but in my example I chose to use the most basic form you could use. A List does not have a fixed size, unlike an array (notice how I initialized the array). Lists are great if you want to add more items later, or if you have no idea beforehand how many items you will need to store. However, in this case, we have the keyboard input, so we know exactly how many items we'll have. Thus: array. It will implicitly tell whoever is reading your code, that you do not intend to add more items later.
I hope this answered some questions, and raised some new ones. See just how deep the rabbit hole goes :P
Use a list or an array. List example:
int numberOfObjects = 3;
List<YourType> listOfObjects = new List<YourType>();
for(int i = 0 ; i < numberOfObjects ; i++ )
{
// Get input and create object ....
// Then add to your list
listOfObjects.Add(element);
}
Here, listOfObjects is a Generic list that can contain a variable number of objects of the type YourType. The list will automatically resize so it can hold the number of objects you add to it. Hope this helps.
If I understood what you are asking you could probably do something like this:
class Foo
{
private static int count;
public string name;
public Foo(...){
name = ++count + "";
}
}
I'm guessing what you're trying to do here, but this is a stab in the dark. The problem I'm having is dealing with the whole "the new objects name should contain a counting number starting from 1" thing. Anyway, here's my attempt:
public class UserInstantiatedClass
{
public int UserSetField1;
public int UserSetField2;
public int UserSetField3;
public int UserSetField4;
public string UserSpecifiedClassName;
}
public static class MyProgram
{
public static void Main(string [] args)
{
// gather user input, place into variables named
// numInstances, className, field1, field2, field3, field4
List<UserInstantiatedClass> instances = new List< UserInstantiatedClass>();
UserInstantiatedClass current = null;
for(int i=1; i<=numInstances; i++)
{
current = new UserInstantiatedClass();
current.UserSpecifiedClassName = className + i.ToString(); // adds the number 1, 2, 3, etc. to the class name specified
current.UserSetField1 = field1;
current.UserSetField2 = field2;
current.UserSetField3 = field3;
current.UserSetField4 = field4;
instances.Add(current);
}
// after this loop, the instances list contains the number of instances of the class UserInstantiatedClass specified by the numInstances variable.
}
}