Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i return IEnumerable<T> from a method

I am developing Interface for a sample project i wanted it to be as generic as possible so i created a interface like below

public interface IUserFactory
{    
    IEnumerable<Users> GetAll();
    Users GetOne(int Id);
}

but then it happened i had to duplicate the interface to do below

public interface IProjectFactory
{    
    IEnumerable<Projects> GetAll(User user);
    Project GetOne(int Id);
}

if you looked at above difference is just types they return, so i created something like below only to find i get error Cannot Resolve Symbol T What am i doing wrong

public interface IFactory
{    
    IEnumerable<T> GetAll();
    T GetOne(int Id);
}
like image 569
Deeptechtons Avatar asked Nov 03 '11 11:11

Deeptechtons


People also ask

How do you use IEnumerable T?

IEnumerable<T> contains a single method that you must implement when implementing this interface; GetEnumerator, which returns an IEnumerator<T> object. The returned IEnumerator<T> provides the ability to iterate through the collection by exposing a Current property.

What is the return type of IEnumerable?

IEnumerable interface Returns an enumerator that iterates through the collection.

Should you return IEnumerable?

To be less colloquial, you can return IEnumerable when you want to make it clear to consumers of your method that they cannot modify the original source of information. It's important to understand that if you're going to advertise this, you should probably exercise care in how the thing you're returning will behave.

How do I get an item from IEnumerable?

We can get first item values from IEnumerable list by using First() property or loop through the list to get respective element. IEnumerable list is a base for all collections and its having ability to loop through the collection by using current property, MoveNext and Reset methods in c#, vb.net.


1 Answers

You need to use a generic interface/class, not just generic methods:

public interface IFactory<T>
{    
    IEnumerable<T> GetAll();
    T GetOne(int Id);
}

Defining a generic type on the interface/class ensures the type is known throughout the class (wherever the type specifier is used).

like image 67
Oded Avatar answered Oct 18 '22 17:10

Oded