How to Initialize IEnumerable<UiElement>?

collections
code

#1

I want to initialize IEnumerable as an empty collection.

I later on put on some values if exists and then do an “IF”.


#2

Hi,

You can’t initialize a variable that is of Interface or Abstract class. Instead, you initialize a class that implements that Interface (f.e. List<T>) and cast it (treat/read/convert it as/to a different type).
Here are some examples how you can cast in VB.Net, depending on circumstances.
Depending on what you want to achieve, you may not even need to cast at all. A class can be treated inline as any of it’s inheriting types (so Base class + all implemented Interfaces). F.e. doing a ForEach over a List, IList, IEnumerable and Array functionally works exactly the same.

An IEnumerable<T> is a readonly collection by design. It’s supposed to be used to iterate over/query a collection (f.e. with LINQ), not to create one.
For the case scenario you’ve described, you’ll be much better off using either an Array or a List<T>, depending if memory microoptimizations are needed or not (usually not and a List<T> will be the better choice).

As a sidenote - if you’d look at most functions that return an IEnumerable, in the method body they use a concrete class like List and then only cast at the end when returning the value, as at that point the collection is complete and the function wants to only return a “view” of it.
Some other info here.

Regards,
Andrzej


#3

Thanks Andrzej.
I was trying to initialize it as a List only but it wasn’t working. I guess I must ve been doing something wrong.
However, It got resolved.

Thanks again