List of Type Interface

Ronald Rex 181 Reputation points
2022-12-13T16:27:21.64+00:00

Hello Friends. I was just wondering if anyone has a lot of experience working with Lists of type Interface and could share some of the interesting things you can use them for. Also, is there a way to sum a column in a List of Interface type? Thanks !!!!

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,594 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,011 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 54,811 Reputation points
    2022-12-13T17:33:15.807+00:00

    Can you provide us a more concrete example of what you're looking for here?

    A list of interfaces?

       public interface IShape {}  
         
       public class Circle: IShape {}  
       public class Rectangle: IShape {}  
       public class Triangle: IShape {}  
         
       var shapes = new List<IShape>();  
       shapes.Add(new Circle());  
       shapes.Add(new Triangle());  
       shapes.Add(new Rectangle());  
    

    To sum a set of anything use the LINQ method Sum.

       var numbers = new [] { 10, 20, 30, 40 };  
       var sum = numbers.Sum();  
    

    It works with any type (interface or otherwise) provided you refer to the property that contains the value you want to sum.

       public interface IMyInterface  
       {  
          int SomeValue { get; set; }  
       }  
         
       var items = new List<IMyInterface>();  
       ...  
         
       var sum = items.Sum(x => x.SomeValue);  
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.