0

I need to implement in C# the following structure from ActionScript3:

objectArray.push({name:"Stx10",category:123 , isSet:false, isEmpty:true});

So that later I can access the objects from the array like this:

String name =objectArray[i].name

So I naturally though about C Sharp Hash Tables but the allow only a single Key -> Value insertion. I can't believe .NET framework has not solution for such a thing... Any help will be greatly appreciated!

3
  • 1
    Not sure if HashTable is the best container to use, have you looked at Dictionary<key, value>? Commented Aug 1, 2011 at 10:01
  • Hashtables also support exactly what you tried to do (apart from not casting object -> String). Are you sure you didn't use a HashSet? Commented Aug 1, 2011 at 10:17
  • What kind of values do you store in the index variable i? Commented Aug 1, 2011 at 10:41

3 Answers 3

2

It looks to me like you're pushing a custom type to an array.

Using an IList will give you a quick Add method in which you can pass a new object of you type such as:

IList<MyType> myCollection = new List<MyType>();

myCollection.Add(new MyType{
Name = "foo",
Category = "bar",
IsSrt = true,
IsEmpty = true
});

UPDATE

Just to add a bit of extra value based on Henk's comment on Porges's answer, here's a way to do the same thing using a dynamic type and thus removing the need for a custom type:

IList<dynamic> myCollection  = new List<dynamic>();
    myCollection.Add(new {  
      Name = "foo",
      Category = "bar",
      IsSet = true,
      IsEmpty = true});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot Jamie and @Porges for your answers !
You're welcome Michael. I've just also added an update on using a dynamic list.
Wow that is awesome Jamie.I really was more interested in a dynamic solution because in my case the parameters vary.Thanks a lot!
Well ,I work with MONO (Unity3D)and it seems that MONO C Sharp doesn't support <dynamic>.Too bad .Will have to stick to your previous solutions.Thanks again.
2

If you're just accessing elements by index as in your example, then you don't need hashed access, you can just use a List<T>.

I'd encapsulate your information into a type like this:

class Thing {
    public string Name {get; set;}
    public int Category {get; set;}
    public bool IsSet {get; set;}
    public bool IsEmpty {get; set;}
}

Then:

objectList.Add(new Thing{Name="Stx10", Category=123, IsSet=false, IsEmpty=true})

// ...

string name = objectList[i].Name;

1 Comment

And an anonymous/dynamic type to hold name , category etc.
0

Don't forget about

  var d=new Dictionary<string, object>();

What's your intention though?

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.