Reputation: 25
There i try to specify bounds of an array:
public string[] scaleChanged()
{
int j =0;
for(int i=0;i<42;i++)
{
if(MinScale == ItemScale[i]) //MinScale is the min value I want to use to start array
{
ItemsScale[j] = MinScale; //ItemScal is an array of 42 string
for(int h =0; h<42-i; h++)
{
ItemScale[j+1] = ItemScale[i];
j++;
if(ItemScale[j] == MaxScale) //MaxScale is my max value I want to use for stop my array
{
return ItemScale[ ???MinScale to MaxScale];
}
}
}
}
}
So I recover 2 value from a server which allow me to specify bounds of my array.
So I try to define a new array with this two values as bounds.I precise this "two values" are always declared anywhere in my ItemScale array (that is why i use comparaison).
Upvotes: 1
Views: 1125
Reputation: 1062780
If really depends what you are trying to do here. The bounds of an array are fixed at creation, and in the case of a vector (string[]
is a vector), it is always zero-based. If you want an actual array, then you'll need to copy out the sub-range into a second array - just new
the array of the correct size, and Array.Copy
the element range you want - i.e. Array.Copy(source, startIndex, destination, 0, count);
. However, there are ways to represent a range without copying:
IEnumerable<T>
- i.e. return source.Skip(firstIndex).Take(count);
Span<T>
or ReadOnlySpan<T>
, i.e. return new Span<string>(source, firstIndex, count)
- a "span" works much like an array, and doesn't require any copying, and is allocation-free; the offset etc is applied appropriately; note that once you have a span, .Slice(...)
creates smaller and smaller sub-sections inside that span, again without any copying or allocations
[ReadOnly]Span<T>
, you can use .ToArray()
to create a new array with those contentsMemory<T>
or ReadOnlyMemory<T>
is effectively "I can give you a span when you want one" - because you can't store a "span" as a field (it is only legal on the stack), but you can store a "memory"ArraySegment<T>
is an older metaphor for expressing an array with offset and count; it relies on the caller doing everything correctlyUpvotes: 3