Home > Software engineering >  How to read this line of code correctly - Interfaces as objects
How to read this line of code correctly - Interfaces as objects

Time:02-22

Given a line such as:

IEnumerable s = new List<int>() {1, 2}; 

I would read this line as: Create a new instance of List where each member must have an int32 data type and name this instance "s" which is of type IEnumerable.

I am not sure if the last part of the sentence is correct or not. I mean the part "which is of type IEnumerable" since Interfaces used to be contracts (with possible implementations in c#8.0 ) and I am not sure if we can correctly refer to them as objects. In fact, the type of "s" in this case is a System.Collections.Generic.List not IEnumerable.

Thank you.

CodePudding user response:

In your code, you define s as a List<int>. It is not correct to say that s has type IEnumerable or even IEnurerable<int>:

using System;
using System.Collections;
using System.Collections.Generic;

namespace types
{
    internal class Program
    {
        static void Main(string[] args)
        {
            IEnumerable s = new List<int>();
            Console.WriteLine(s.GetType());
            if(s is IEnumerable<int> enumerableType)
                Console.WriteLine(enumerableType.GetType());
            if (s is List<int> listType)
                Console.WriteLine(listType.GetType());
        }
    }
}

Output:

System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]

Perhaps what the OP is not understanding is that List implements (among others) the interface IEnumerable---from the source code:

public class List<T> : ICollection<T>, IEnumerable<T>, IEnumerable, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection, IList

I am sure that I am explaining this all wrong in terms of implementation details and that the .NET honchos will correct me, but what this means in practice is that you can create a variable of type IEnumerable<T> that in fact is a List<T> and treat it as either type. But, since you declared it as IEnurable<T> you cannot use it as a List<T> without some extra syntax.

For example:

IEnumerable<int> s = new List<int>();
s.Add(1);

will not compile because IEnumerable<T> has no definition for Add. But you can do this:

IEnumerable<int> s = new List<int>();
if(s is List<int> list)
     list.Add(1);

Much more practical is simply to declare it as List<T> because all IEnumerable does is enumerate and since List implements the interface you get that functionality without any extra code.

CodePudding user response:

You are reading it perfectly fine. Given the following expression:

IEnumerable s = new List<int>() {1, 2}; 

we say that s is a variable of type IEnumerable that refers to an instance of List<int> containing two elements.

  • Related