Why it is not ok to use IEnumerable<T> as a type for a property within a class
for instance something like
public class Example
{
public IEnumerable<Int32> Ids {get; private set;}
publicIEnumerable<string> Names {get; private set;}
}
Sorry the problem was not that it wasn't compiling, I missed the public accessors on writing the stuff here, the question was why not to use IEnumerable for a property. But as I read further, I realized that if we only need something to iterate through and not modify (add, remove) than this (using IEnumerable ) is perfectly acceptable.
The problem is that the default accessibility of members in classes is already private, so your code is equivalent to:
public class Example
{
private IEnumerable<int> Ids {get; private set;}
private IEnumerable<string> Names {get; private set;}
}
That fails to compile because when you include an extra access modifier for a getter or setter, it has to be more restrictive than the overall access of the property. It isn't in this case.
If you make the overall property public though, it will compile with no problems:
public class Example
{
public IEnumerable<int> Ids {get; private set;}
public IEnumerable<string> Names {get; private set;}
}
(That's assuming you have a using directive for the System.Collections.Generic namespace, of course.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With