Class and array properties

E

exitus

Is there a way to dynamically resize an array along with maintaining
its contents similar to VB's REDIM PRESERVE statement in C#? My
problem is, the user won't be sure how big the string array (sTest) is
initially. As stated in the code below, when the class is
instantiated, the string array is initialized to null. Is it possible
to have the user "set" a value in the array and the object would resize
the array automatically? For instance:

using System;

namespace Class1
{
public class Class1
{
private string[] sTest;

public string[] Test
{
get { return this.sTest; }
}

public UserProxy()
{
this.sTest = null;
}
}
}

Class1 tmp = new Class1();

tmp.Test[0] = "TEST";

I want the tmp object to be able to automatically create/resize its
sTest array and/or overwrite the value at the current location
specified, without destroying any other value in the rest of the array?
In the set accessor, how can I "see" what index the user specified?
Is what I ask even possible or is there an easier way?

Any help would be greatly appreciated.

Thanks,
Exitus
 
G

gmiley

I've always been a fan of creating a custom class that inherits from
System.Collections.CollectionBase

You can implement whichever sets of functionality you want, and type
your collections items however you want such as: Add(), Remove(),
RemoveAt(), IndexOf(), etc...

I try to only use regular arrays for quick processing/parsing. For more
complex data structures I usually stick with the CollectionBase base
class.
 
J

Jon Skeet [C# MVP]

Is there a way to dynamically resize an array along with maintaining
its contents similar to VB's REDIM PRESERVE statement in C#?

No. Even VB.NET's REDIM PRESERVE doesn't really resize the array - it
creates a new array of the bigger size, and copies everything into it,
just as you can do in C#. Note that any other variables which referred
to the original array still do.

However, it's easier to use an IList (eg ArrayList) in most cases. In
1.1 that's not a strongly-typed solution, but in 2.0 you can use
List<Foo> for a list of references to objects of type Foo.

I want the tmp object to be able to automatically create/resize its
sTest array and/or overwrite the value at the current location
specified, without destroying any other value in the rest of the array?
In the set accessor, how can I "see" what index the user specified?
Is what I ask even possible or is there an easier way?

No, what's you're asking isn't possible - there's no set accessor
involved, it's just array access.
 
J

John Bailo

Use an ArrayList and add Class1 objects to it. You can then add, search
and sort.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top