Objects in C # arraylist

I come from the Javascript background, which is probably good, although so far it’s bad.

In Javascript, I have:

function doStuff(){ var temp = new Array(); temp.push(new marker("bday party")); alert(temp[0].whatsHappening); // 'bday party' would be alerted } function marker(whatsHappening) { this.whatsHappening = whatsHappening; } 

Now I would like to do the same in C #. I created a class:

 class marker { public string whatsHappening; public marker(string w) { whatsHappening = w; } } 

and add a new object, but I cannot name the data the same way:

 ArrayList markers = new ArrayList(); markers.Add(new marker("asd")); string temp = markers[0].whatsHappening; // This last bit isn't allowed 
+4
source share
4 answers

Use a generic List<T> instead:

 List<marker> markers = new List<marker>(); markers.Add(new marker("asd")); string temp = markers[0].whatsHappening; 
+5
source

ArrayList is weakly typed. This means that all elements of the array are objects. You need to give them to your class:

 string temp = ((marker)markers[0]).whatsHappening; 

You should use a List<marker> instead.

+4
source

To use it from an ArrayList , you must first apply it to the appropriate type. ArrayList saves elements as an object .

 var item = (marker)markers[0]; // item.Foo is now accessible 

However, assuming you are using a C # version released since 2005 (that is, C # 2.0+), you would be better off using List<T> , where T is the type of object. It is strongly typed, can only store elements of type T and does not require operations to complete operations.

 List<marker> markers = new List<marker>(); markers.Add(new marker()); // legal markers.Add(1); // not legal, but would be allowed with ArrayList 

List<T> is available in the System.Collections.Generic namespace.


Unrelated, since you're new to C #, learn the language conventions that almost all C # developers adhere to. A few basic ones: class names, properties, methods - PascalCased, private members, parameters, local variables - camelCased, and class data is displayed as properties, and not as public fields.

 public class Marker { public string WhatsHappening { get; set; } // exposed as property string foo; // member field, is implicitly private public void DoFrobbing(Bar thingToFrob) { int localVariable; } } 
+3
source

ArrayList contains a list of Object s. Try using the generic System.Collections.Generic.List<T> :

 List<marker> markers = new List<marker>(); 
+1
source

All Articles