4

I'm coming from a Javascript background which possibly is a good thing although so far it's proving to be a bad thing.

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

I would now like to do the same thing in C#. I have set up a class:

class marker
{
    public string whatsHappening;

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

and add a new object, but I can't seem to call the data in the same way:

ArrayList markers = new ArrayList();

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

4 Answers 4

5

Use a generic List<T> instead:

List<marker> markers = new List<marker>();
markers.Add(new marker("asd"));
string temp = markers[0].whatsHappening;
Sign up to request clarification or add additional context in comments.

Comments

4

ArrayList is weakly typed. That means, all items in the array are objects. You need to cast them to your class:

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

You should use a List<marker> instead.

Comments

3

To use it from an ArrayList, you must first cast it to the appropriate type. ArrayList stores items as object.

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

However, assuming you're using a version of C# released since 2005 (ie., C# 2.0+), you will be better off using List<T>, where T is the type of the object. It's strongly typed, can only store items of type T, and does not require casts to perform 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 conventions of the language that virtually all C# developers adhere to. A few basic ones: class names, properties, methods are PascalCased, private members, parameters, local variables are camelCased, and class data is exposed as properties, not as publicly accessible 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;
    }
}

Comments

1

ArrayList holds a list of Objects. Try to use the generic System.Collections.Generic.List<T>:

List<marker> markers = new List<marker>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.