Home > database >  Finding the property value in generic c#
Finding the property value in generic c#

Time:05-02

I am trying to find a property of a class in a generic method.

Class abc
-property Name : xyz

I have a method like :

public bool findItem<T> (IEnumerable<T> items) where T : Data
{
   if (typeof(T) == typeof(abc))
   {
       // Code comes inside the loop here
       // how to find something like items.First().xyz
   }
}

I want to find the property value for the first item but it doesnt work (there is no autosuggest too).

While debugging (in immediate window), I can see my object with class Name when i do items.First().

I tried items.First()["xyz"] but doesnt work. (Cannot apply indexing with [] to an expression of type T)

CodePudding user response:

You certainly could do something like this:

public bool FindItem<T>(IEnumerable<T> items)
{
    if (items is IEnumerable<Abc> abcs)
    {
        int first = abcs.First().Xyz;
        return true;
    }
    else if (items is IEnumerable<Def> defs)
    {
        int first = defs.First().Ghi;
        return true;
    }
    return false;
}

However, that's not the normal way to do it. Normally you'd just use overloads:

public bool FindItem(IEnumerable<Abc> items)
{
    int first = items.First().Xyz;
    return true;
}

public bool FindItem(IEnumerable<Def> items)
{
    int first = items.First().Ghi;
    return true;
}

CodePudding user response:

//Try This! It should work 
public bool FindItem<T>(IEnumerable<T> items) where T : Data
{
        if (typeof(T) == typeof(Abc))
        {
            var abcItems = (IEnumerable<Abc>)items;

            var xyz = abcItems.FirstOrDefault().Xyz;
        }

        return true;
}
  •  Tags:  
  • c#
  • Related