Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have fixed typed ArrayList in C#, just like C++?

Tags:

c#

arraylist

I have an ArrayList which contains fixed type of objects. However everytime I need to extract an object a particular index, I need to typecast it to my user defined type from object type.

Is there a way in C# to declare ArrayList of fixed types just like Java and C++, or is there a work around to avoid the typecasting everytime?

Edit:

I apologize I forgot mentioning that I require the datastructure to be thread-safe, which List is not. Otherwise I would have just used a normal Array. But I want to save myself from the effort of explicitly locking and unlocking while writing the array.

So I thought of using ArrayList, synchronize it, but it requires typecasting every time.

like image 639
Kazoom Avatar asked Mar 02 '10 03:03

Kazoom


2 Answers

You could use a List. The List class takes advantage of generics to make a strongly typed collection.

To use, just call new List< Type you want to use >() like this:

List<string> myStringList = new List<string>();

MSDN has a quick article on some ways you can make collections thread safe.

like image 156
Corey Sunwold Avatar answered Oct 18 '22 10:10

Corey Sunwold


Take a look at System.Collections.Generic.List

http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

like image 32
Bryan Matthews Avatar answered Oct 18 '22 08:10

Bryan Matthews