Attribute lost with yield

Posted by Nelson on Stack Overflow See other posts from Stack Overflow or by Nelson
Published on 2010-04-07T17:29:06Z Indexed on 2010/04/07 17:33 UTC
Read the original article Hit count: 315

Filed under:
|
|
|

Here's an interesting one... There is some code that I'm trying to convert from IList to IEnumerable:

[Something(123)]
public IEnumerable<Foo> GetAllFoos()
{
  SetupSomething();

  DataReader dr = RunSomething();
  while (dr.Read())
  {
    yield return Factory.Create(dr);
  }
}

The problem is, SetupSomething() comes from the base class and uses:

Attribute.GetCustomAttribute(new StackTrace().GetFrame(1).GetMethod(), typeof(Something))

Yield ends up creating MoveNext(), MoveNext() calls SetupSomething(), and MoveNext() does not have the [Something(123)] attribute.

I can't change the base class, so it appears I am forced to stay with IList or implement IEnumerable manually (and add the attribute to MoveNext()). Is there any other way to make yield work in this scenario?

© Stack Overflow or respective owner

Related posts about c#

Related posts about attributes