Whidbey C# Generics/Iterators Question

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Kamen Yotov (kamen_at_yotov.org)
Date: 02/08/04


Date: Sun, 8 Feb 2004 02:26:50 -0500

Hello,
I got my hands on the PDC preview version of whidbey and I think I managed
to break the compiler/runtime with my first Generics/Iterators attempt. The
reason I am posting it here is that I might be wrong, in which case, please
correct me!

The following program prints garbade instead the intended 5,6,1. I think it
is printing the integer values of the pointers which represent some
references... Any ideas?

using System;
using System.Collections.Generic;

namespace test2
{
 class List<T>: IEnumerable<T>, IEnumerable<ListNode<T>>
 {
  protected ListNode<T> _head;
  protected ListNode<T> _last;

  public List ()
  {
  }

  public void Add (T _value)
  {
   if (_head == null)
    _head = _last = new ListNode<T>(_value, null);
   else
    _last = _last.Next = new ListNode<T>(_value, null);
  }

  IEnumerator<T> IEnumerable<T>.GetEnumerator()
  {
   for (ListNode<T> _current = _head; _current != null; _current =
_current.Next)
    yield _current.Value;

   /*
   foreach (ListNode<T> n in (IEnumerable<ListNode<T>>)this)
    yield n.Value;
   */
  }

  IEnumerator<ListNode<T>> IEnumerable<ListNode<T>>.GetEnumerator()
  {
   for (ListNode<T> _current = _head; _current != null; _current =
_current.Next)
    yield _current;
  }
 }

 class ListNode<T>
 {
  protected T _value;
  protected ListNode<T> _next;

  public ListNode (T _value, ListNode<T> _next)
  {
   Value = _value;
   Next = _next;
  }

  public T Value
  {
   get
   {
    return _value;
   }
   set
   {
    _value = value;
   }
  }

  public ListNode<T> Next
  {
   get
   {
    return _next;
   }
   set
   {
    _next = value;
   }
  }
 }

 class Class1
 {
  [STAThread]
  static void Main(string[] args)
  {
   List<int> l = new List<int>();

   l.Add(5);
   l.Add(6);
   l.Add(1);

   foreach (int q in (IEnumerable<int>)l)
    Console.WriteLine(q);
  }
 }
}



Relevant Pages

  • Re: Strange code in Queue class in .NET framework
    ... method of the generic Queue class in the .NET framework. ... public void Enqueue ... One possible reason for this might be as a sort of clever "high bandpass ...
    (microsoft.public.dotnet.framework)
  • Polymorphism
    ... I presume the reason is that the type to cast to is not known at ... compile time. ... public void foo{ ...
    (comp.lang.java.programmer)
  • skip super.paintComponent()
    ... there a compelling reason for that or can I rely on the proper execution of ... class MyFirstComponent extends javax.swing.JComponent ... public void paintComponent ...
    (comp.lang.java.programmer)
  • Re: Polymorphism
    ... If this is the reason, ... > public void foo{ ... which tests if its argument is a String or Collection and call the ...
    (comp.lang.java.programmer)