c# - Warning - does not implement the 'collection' pattern -


i making collection, implementing ienumerable explicitly , trying iterate within:

public class mycollection<t> : ienumerable<t>, ienumerable {     ienumerator ienumerable.getenumerator() => getenumerator();     ienumerator<t> ienumerable<t>.getenumerator() => getenumerator();     ienumerator<t> getenumerator() { yield return default(t); } // test      public void test()     {         foreach (var item in this) { } // here warning     } } 

i compiler warning @ this:

warning cs0279 'mycollection' not implement 'collection' pattern. 'mycollection.getenumerator()' either static or not public.

hell yes, it's not public. why should be? can make public, it's not needed foreach outside of type:

foreach (var item in new mycollection<string>()) { } // no warning 

am doing wrong?

the warning exists because c# compiler can handle foreach in number of different ways. 1 of ways find getenumerator method suitable return type. that's checked before compiler checks whether or not type of expression implements ienumerable or ienumerable<t>.

in case, gets far finding single parameterless getenumerator method, it's not public. c# specification recommends warning @ point, may have intended usable foreach. c# 5 spec, section 8.8.4, emphasis mine:

  • perform overload resolution using resulting method group , empty argument list. if overload resolution results in no applicable methods, results in ambiguity, or results in single best method method either static or not public, check enumerable interface described below. it recommended warning issued if overload resolution produces except unambiguous public instance method or no applicable methods.

any of following solve problem:

  • rename getenumerator getenumeratorimpl or similar:

    ienumerator ienumerable.getenumerator() => getenumeratorimpl(); ienumerator<t> ienumerable<t>.getenumerator() => getenumeratorimpl(); ienumerator<t> getenumeratorimpl() { yield return default(t); } 
  • don't use explicit interface implementation ienumerable<t>.getenumerator() - put implementation there

    ienumerator ienumerable.getenumerator() => getenumerator(); public ienumerator<t> getenumerator() => { yield return default(t); } 
  • put implementation in ienumerable<t>.getenumerator, cast this ienumerable<t> in ienumerable.getenumerator call it:

    ienumerator ienumerable.getenumerator() => ((ienumerable<t>) this).getenumerator(); ienumerator<t> ienumerable<t>.getenumerator() => { yield return default(t); } 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -