Setting array items from a custom created class - c#

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];

Related

How can I find an Index in an array using a value that exists in another array and THAT array?

I have a c# class that looks like this:
public class MemberData
{
public int meme_ck;
public string meme_name;
public bool meme_active;
public MemberData(int ck2, string name2, bool active2)
{
meme_ck = ck2;
meme_name = name2;
meme_active = active2;
}
}
I have made two arrays out of that class:
private MemberData[] memarray1 = new MemberData[10000];
private MemberData[] memarray2 = new Memberdata[10000];
Over the course of my application I do a bunch of stuff with these two arrays and values change, etc. Member's name or active status may change which results in the ararys becoming different.
Eventually I need to compare them in order to do things to the other one based on what results are kicked out in the first one.
For example, member is de-activated in the first array based on something application does, I need to update array 2 to de-activate that same member.
I am trying to use some database design philosphy with the int CK (contrived-key) to be able to rapidly look up the entry in the other array based on the CK.
Since I can't figure it out I've had to resort to using nested for loops like this, which sucks:
foreach (Memberdata md in memarray1)
{
foreach (Memberdatamd2 in memarray2)
{
if (md.ck = md2.ck)
{
//de-activate member
}
}
}
Is there a better way to do this? I just want to find the index in the second array based on CK when I have the CK value from the first array.
Any other tips or advice you have about structure would be appreciated as well. Should I be using something other than arrays? How would I accomplish this same thing with Lists?
Thanks!
Should I be using something other than arrays?
Yes. Don't use arrays; they are seldom the right data structure to use.
How would I accomplish this same thing with Lists?
Lists are only marginally better. They don't support an efficient lookup-by-key operation which is what you need.
It sounds like what you want is instead of two arrays, two Dictionary<int, MemberData> where the key is the ck.
I totally agree with Eric Lippert's answer above. It is better you do not use Array.
Same thing can be achieved using List<MemberData>. You can use LINQ as well to query your DataStructure.
Following is one of the way just to achieve your result using array
class Program
{
static MemberData[] memarray1 = new MemberData[10000];
static MemberData[] memarray2 = new MemberData[10000];
static void Main(string[] args)
{
for (int i = 0; i < memarray1.Length; i++)
{
memarray1[i] = new MemberData(i + 1, "MemName" + i + 1, true);
memarray2[i] = new MemberData(i + 1, "MemName" + i + 1, true);
}
// SIMULATING YOUR APP OPERATION OF CHANGING A RANDOM ARRAY VALUE IN memarray1
int tempIndex = new Random().Next(0, 9999);
memarray1[tempIndex].meme_name = "ChangedName";
memarray1[tempIndex].meme_active = false;
//FOR YOUR UDERSTADNING TAKING meme_ck IN AN INTEGER VARIABLE
int ck_in_mem1 = memarray1[tempIndex].meme_ck;
//FINDING ITEM IN ARRAY2
MemberData tempData = memarray2.Where(val => val.meme_ck == ck_in_mem1).FirstOrDefault();
// THIS IS YOUR ITEM.
Console.ReadLine();
}
}

Using String Array As Object Argument

So I have a class that has an argument of a string array. What I want to do is store multiple strings to this array that is part of this class. The code looks something like this:
//Class part of it. Class is called "Event"
public class Event
{
public string[] seats = new string [75];
public Event(string[] seats)
{
this.seats = seats;
}
}
// the main code that uses "Event" Class
string[] seatnumber = new string[75];
Event show = new Event (seatnumber[]); //And that is where the error comes in.
Any help would be greatly appreciated!
Remove the brackets from seatnumber when putting it in the Event constructor.
For reference.
When you call an array, the variable name does not need the brackets [].
Event show = new Event(seatnumber);
It the same as you called earlier in your code:
this.seats = seats;
seats is also an array, though you haven't added the [] when you called it - so no error.

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;
}
);

filling an array in a struct 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'};

how to create multiple objects and enumerate them in c#

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.
}
}

Categories

Resources