Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing object's property inside generic method [duplicate]

Tags:

c#

How can access the property of an object inside generic method?
I can't use where T: A because this method will receive different objects, but all objects have a common property to work on.
(I also can't make for them a common interface)

public class A
{
    public int Number {get;set;}
}


List<A> listA = new List<A>{
                new A {Number =4},
                new A {Number =1},
                new A {Number =5}
};

Work<A>(listA);

public static void Work<T>(List<T> list1)
{
    foreach(T item in list1)
    {
        do something with item.Number;
    }
}

An update: I need also to set the property

like image 970
asker Avatar asked Dec 06 '25 08:12

asker


2 Answers

You have a few choices:

  • Make a common interface.
  • Use reflection.
  • Use the dynamic type in .NET 4.

I know you said you can't do the first, but it's the best option for performance and maintainability so please reconsider if its possible before choosing one of the other methods. Remember that even if you can't modify the original code you might still be able to choose the first option. For example if your classes are partial classes you can implement the interface in another file:

File 1:

// Automatically generated code that you can't change.
partial class A
{
    public int Number { get; set; }
}

File 2:

interface IHasNumber
{
    int Number { get; set; }
}

partial class A : IHasNumber
{
}

If the original class isn't defined as partial you could write wrapper classes around them that implement the interface.

Once you have the common interface you can change your generic constraint to require this interface:

where T : IHasNumber
like image 114
Mark Byers Avatar answered Dec 07 '25 20:12

Mark Byers


If you don't need the list - just the items, I would use a projection outside the method:

static void Main()
{
    List<A> listA = new List<A>{
            new A {Number =4},
            new A {Number =1},
            new A {Number =5}
    };

    Work(listA.Select(a => a.Number));

}
public static void Work(IEnumerable<int> items)
{
    foreach (number item in items)
    {
        // do something with number;
    }
}

If you need the list - a projection inside the method via a selector:

static void Main()
{
    List<A> listA = new List<A>{
            new A {Number =4},
            new A {Number =1},
            new A {Number =5}
    };

    Work(listA, a => a.Number);

}
public static void Work<T>(IList<T> list, Func<T, int> selector)
{
    foreach (T obj in list)
    {
        int number = selector(obj);
        // do something with number;
    }
}
like image 34
Marc Gravell Avatar answered Dec 07 '25 21:12

Marc Gravell



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!