Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate though Generic List in C#

Tags:

c#

generics

public class Item
{
        private int  _rowID;
        private Guid _itemGUID;

        public Item() { }

        public int Rid
        {
            get
            {
                return _rowID;
            }
            set {  }

        }

        public Guid IetmGuid
        {
            get
            {
                return _itemGuid;
            }
            set
            {
                _itemGuid= value;
            }

        }

}    

The above is my custom object.

I have a list:

List<V> myList = someMethod;

where V is of type Item, my object.

I want to iterate and get the properties as such

foreach(V element in mylist)
{
   Guid test = element.IetmGuid; 
}

When I debug and look at the 'element' object I can see all the properties in the 'Quickwatch' but I cannot do element.IetmGuid.


2 Answers

Are you putting a constraint on the generic type V? You'll need to tell the runtime that V can be any type that is a subtype of your Item type.

public class MyGenericClass<V>
  where V : Item  //This is a constraint that requires type V to be an Item (or subtype)
{
  public void DoSomething()
  {
    List<V> myList = someMethod();

    foreach (V element in myList)
    {
      //This will now work because you've constrained the generic type V
      Guid test = element.IetmGuid;
    }
  }
}

Note, it only makes sense to use a generic class in this manner if you need to support multiple kinds of Items (represented by subtypes of Item).

like image 157
akmad Avatar answered Sep 07 '25 23:09

akmad


Try declaring your list like this:

List<Item> myList = someMethod;
like image 26
Daniel M Avatar answered Sep 08 '25 00:09

Daniel M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!