Using String Array As Object Argument - c#

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.

Related

C# getting array with a string name?

So here's a hypothetical. From someone fairly new to the whole C# and Unity thing:
Suppose for a moment that I have a series of string[] arrays. All of which have similar naming convention. For example:
public string[] UndeadEntities =
{
// stuff
};
public string[] DemonEntities =
{
// stuff
};
Now suppose I want to call one of them at random, I have another list that contains the names of all of those arrays and I return it at random.
My problem is that I grab the name from the array and it's a string, not something I can use. So my question is this:
is there any way for me to use this string and use it to call the above mentioned arrays.
Something like this is what I'm up to but unsure where to go from here and I really would like to avoid making a massive series of If Else statements just for that.
public string[] EnemiesType = { // list of all the other arrays }
public string enemiesTypeGeneratedArrayName = "";
public void GenerateEncounterGroup()
{
enemiesTypeGeneratedArrayName = EnemiesType[Random.Range(0, 12)];
}
Can I nest arrays inside of other arrays? Is there another alternative?
I'm not sure if it is possible at all but if it is, I'll take any pointers as to where to go from there. Thanks.
There are several solutions to your specific problem, an easy one is using Dictionaries:
A Dictionary is a data structure wher you have a key (usually a string) and a value (whatever type you may want to store).
What you can do is at start, initialized a Dictionary were each key is your enemy type, and the value it store is your array, something like:
Dictionary<string, string[]> enemyArrays= new Dictionary<string, string[]>();
.
void Start()
{
enemyArrays["typeA"] = myArrayA;
enemyArrays["typeB"] = myArrayB;
}
Then when you need to get that array, just:
enemiesTypeGeneratedArrayName = EnemiesType[Random.Range(0, 12)];
string[] myRandomArray =enemyArrays[enemiesTypeGeneratedArrayName];
string randomEnemy = myRandomArray[index];
Here you can read more about Dictionary class if you want.
There are other ways to do it, but I think this one is pretty easy to implement in the code you already made, and Dicionaries are cool haha.
I hope is clear:)

What do square brackets mean in this context in C#?

What do the square brackets mean in a new expression in C# as follows:
public class MyClass
{
public string Name { get; set; }
}
// ...
var x = new MyClass[0]; // <-- what is this?
This is an array declaration
The use of var just allows the compiler to decide on the type
MyClass[] classArray = new MyClass[0];
The 0 inside the [] indicates that the number of array 'spaces' is 0
var classArray = new MyClass[5];
This will create an array of length 5, and the use of var will allow the compiler to decide on the type, which will be MyClass[]
You can access each place in the array I created above by using indexers, mentioned in another answer, similar to this, let's say MyClass has a property called name with public get and set accessors(stupid example I know)
classArray[1] = new MyClass();
classArray[1].Name = "Daniel's class";
This allows us to access the MyClass object held in the second array placement, this is indexing
We can also create an array like this, let's say that the MyClass has a constructor that takes a string for the Name property
var x = new [] {
new MyClass("Daniels"),
new MyClass("Yours"),
new MyClass("Ours")
};
Forgive me for my bad examples

c#, class with properties of type string array, set not working

I have a class that has several properties, a couple which are string arrays. When the following statement:
MyObj.Str1[1] = "AAA";
MyObj.Str1[1] does not contain "AAA". Using debug breakpoints, I see the set routine doesn't execute (the get routine does execute).
The property looks like:
public string[] Str1
{
get { return bdr.GetArrVal(1, 25, 7); }
set { bdr.SetArrVal(1, 25, 7, value); }
}
GetArrVal() builds and returns a string array from class internal data. SetArrVal() sets class internal data from the incoming array.
I tried using indexers but had too many problems passing class internal data into the class describing Str1.
Please note that the statement
MyObj.Str1 = arr1;
works, where arr1 is a string array. The program breaks at the set routine.
All of this makes me think I cant do what I want. Can you assign a single element of a string-array property of an object?
MyObj.Str1 is a string (which is a group of characters) and MyObj.Str1[1] is the char on the second index of that string. You are assigning "AAA" three elements to a single character. This does not make any sense if you are trying to "assign a single element of a string-array property of an object?"
Str1 is the property name as posted by you public string[] Str1 { which returns a string[]. So when you say MyObj.Str1[1] = "AAA"; you are actually trying to set a array element returned by Str1 property and not the property itself and thus the statement MyObj.Str1 = arr1; works fine.

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

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