Re: Array.Clear vs List<>.Clear
- From: "Nicholas Paldino [.NET/C# MVP]" <mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 4 Oct 2007 11:32:04 -0400
Lee,
There isn't a mechanism to do this, but writing your own is easy:
public static void ClearList<T>(List<T> list, int index, int length)
{
// Cycle through the list and set the item to the default.
for (; index < (index + length); ++index)
{
// Set the item in the list to the default value.
list[index] = default(T);
}
}
--
- Nicholas Paldino [.NET/C# MVP]
- mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx
"Lee Crabtree" <lcrabtree@xxxxxxxxx> wrote in message
news:%2377wqmpBIHA.4568@xxxxxxxxxxxxxxxxxxxxxxx
This seems inconsistent and more than a little bizarre.
Array.Clear sets all elements of the array to their default values (0,
null, whatever), whereas List<>.Clear removes all items from the list.
That part makes a reasonable amount of sense, as you can't actually take
items away from an Array. However, there doesn't seem to be a way to
perform the same operation in one fell swoop on a List<>.
For example:
byte[] byteArr = new byte[10];
...things happen and bytes get set...
Array.Clear(byteArr, 0, 10);
Now all the bytes are set to 0.
But if you use a List<byte>:
List<byte> byteList = new List<byte>(new byte[10]);
...things happen and bytes get set...
There's no way to reset all the bytes, so you're forced to iterate over
the list. Now, I'm sure that the performance hit of having to run a for
loop across the list isn't incredible. But aside from the apparent
inconsistency, I have to wonder if there isn't some mechanism to do the
same thing to a generic List.
Lee Crabtree
.
- Follow-Ups:
- Re: Array.Clear vs List<>.Clear
- From: Lee Crabtree
- Re: Array.Clear vs List<>.Clear
- From: Lee Crabtree
- Re: Array.Clear vs List<>.Clear
- References:
- Array.Clear vs List<>.Clear
- From: Lee Crabtree
- Array.Clear vs List<>.Clear
- Prev by Date: Re: Array.Clear vs List<>.Clear
- Next by Date: Re: Array.Clear vs List<>.Clear
- Previous by thread: Re: Array.Clear vs List<>.Clear
- Next by thread: Re: Array.Clear vs List<>.Clear
- Index(es):
Relevant Pages
|