Hello all.
I have to implement IEnumerator interface in my (static) class. But
compilers throws me an error:
'GetEnumerator' : cannot declare instance members in a static class
For example:
private static List<Product_pr oductsList;
public static List<ProductPro ductsList
{
get
{
if (_productsList == null)
_productsList = new List<Product>() ;
return _productsList;
}
set { _productsList = value; }
}
public IEnumerator GetEnumerator()
{
foreach (Product p in _productsList)
{
yield return p;
}
}
That's why I have question: Can I implement Iterator with static
classes other way?
Thanks in advance 8 3413
dtarczynski wrote:
<snip>
That's why I have question: Can I implement Iterator with static
classes other way?
No. You can't implement any non-empty interface in a static class, as
an interface *insists* on certain instance members being present, and a
static class *prevents* any instance members being present.
Jon
Not really. The problem is that the foreach statement expects an instance
variable and not a type name. So, this code is illegal:
using System;
using System.Collecti ons;
using System.Collecti ons.Generic;
namespace ConsoleApp
{
static class EnumeratorTest
{
private static List<intm_IntLi st = new List<int>(new int[] { 0, 1,
2, 3, 4, 5, 6, 7, 8, 9 });
public static IEnumerator GetEnumerator()
{
foreach (int i in m_IntList)
yield return i;
}
}
class Program
{
static void Main(string[] args)
{
foreach (int i in EnumeratorTest)
Console.WriteLi ne(i);
}
}
}
This raises the following compiler error: "'ConsoleApp.En umeratorTest' is
a 'type' but is used like a 'variable'"
However, you *can* add a ForEach method similar to the way it is done by
List<T>.ForEach (). For example:
using System;
using System.Collecti ons;
using System.Collecti ons.Generic;
namespace ConsoleApp
{
static class EnumeratorTest
{
private static List<intm_IntLi st = new List<int>(new int[] { 0, 1,
2, 3, 4, 5, 6, 7, 8, 9 });
public static void ForEach(Action< intaction)
{
foreach (int i in m_IntList)
action(i);
}
}
class Program
{
static void Main(string[] args)
{
EnumeratorTest. ForEach(delegat e(int i) { Console.WriteLi ne(i); });
}
}
}
Best Regards,
Dustin Campbell
Developer Express Inc.
No. You can't implement any non-empty interface in a static class, as
an interface *insists* on certain instance members being present, and
a static class *prevents* any instance members being present.
You don't have to implement an interface to create a GetEnumerator() method
that uses an iterator. This code works fine:
using System;
using System.Collecti ons;
using System.Collecti ons.Generic;
namespace ConsoleApp
{
class EnumeratorTest
{
private List<intm_IntLi st = new List<int>(new int[] { 0, 1, 2, 3, 4,
5, 6, 7, 8, 9 });
public IEnumerator GetEnumerator()
{
foreach (int i in m_IntList)
yield return i;
}
}
class Program
{
static void Main(string[] args)
{
EnumeratorTest instance = new EnumeratorTest( );
foreach (int i in instance)
Console.WriteLi ne(i);
}
}
}
Best Regards,
Dustin Campbell
Developer Express Inc.
There's a trick with static functions that return enumerators you can
use.
static class myStaticClass
{
static private object[] myIterable;
public static IEnumerable<obj ectMyStaticEnum erable() // a method
that returns an enumerable
{
foreach(object obj in myIterable)
{
yield return obj;
}
}
}
this can be used as follows:
foreach (obj in myStaticClass.M yStaticEnumerab le())
{
...
}
I'm pretty sure that mess'll work, though I haven't tested it myself.
dtarczynski wrote:
Hello all.
I have to implement IEnumerator interface in my (static) class. But
compilers throws me an error:
'GetEnumerator' : cannot declare instance members in a static class
For example:
private static List<Product_pr oductsList;
public static List<ProductPro ductsList
{
get
{
if (_productsList == null)
_productsList = new List<Product>() ;
return _productsList;
}
set { _productsList = value; }
}
public IEnumerator GetEnumerator()
{
foreach (Product p in _productsList)
{
yield return p;
}
}
That's why I have question: Can I implement Iterator with static
classes other way?
Thanks in advance
Dustin Campbell <du*****@no-spam-pleasedevexpres s.comwrote:
No. You can't implement any non-empty interface in a static class, as
an interface *insists* on certain instance members being present, and
a static class *prevents* any instance members being present.
You don't have to implement an interface to create a GetEnumerator() method
that uses an iterator.
That's true. You do, however, have to have an instance method - which
runs into exactly the same issue.
--
Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
That's true. You do, however, have to have an instance method - which
runs into exactly the same issue.
That is the problem. Of course, this begs the question why a static class
is needed in the first place. It seems counterintuitiv e for a collection
class to be static since you can't make it enumerable and you can't have
static indexers.
Best Regards,
Dustin Campbell
Developer Express Inc.
Either way, if static-like behaviour is needed, C# has easy idioms for
Singletons. That is, define an instance class, but make the
constructor private - and then give the class itself a static
constructor which in turn constructs the instance object and stores it
in a public static field. Alternately, one can use a property and make
it lazily instantiated, rather than using the static constructor to
construct the single instance object.
Still, I prefer just using a generator to include a method that returns
an IEnumerable if static semantics are desired.
Dustin Campbell wrote:
That's true. You do, however, have to have an instance method - which
runs into exactly the same issue.
That is the problem. Of course, this begs the question why a static class
is needed in the first place. It seems counterintuitiv e for a collection
class to be static since you can't make it enumerable and you can't have
static indexers.
Best Regards,
Dustin Campbell
Developer Express Inc.
Either way, if static-like behaviour is needed, C# has easy idioms for
Singletons. That is, define an instance class, but make the
constructor private - and then give the class itself a static
constructor which in turn constructs the instance object and stores it
in a public static field. Alternately, one can use a property and
make it lazily instantiated, rather than using the static constructor
to construct the single instance object.
Still, I prefer just using a generator to include a method that
returns an IEnumerable if static semantics are desired.
Sure, or even the old System.Collecti ons.ICollection interface.
Best Regards,
Dustin Campbell
Developer Express Inc. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Gregory Bond |
last post by:
I'm trying to extend Python with an iterator class that should be
returned from a factory function.
For some reason the iterator object is not being properly initialised if
the iterator is created in a C function. It works just fine if the
object is created using the class contructor
Trying to minimise the cut-n-paste, but:
> typedef struct {
|
by: Alexander Stippler |
last post by:
Hi,
I have to design some two dimensional iterators and I'm not quite sure about
the design. I'd like to have the iterators mostly STL-like. The STL does
not contain two dimensional iterators, I think. I'm not sure, what is the
best way of design and usage syntax.
Is there a good reference or example online? How could such an iterator look
like for the equivalent of std::vector, lets say my::matrix to "exploit"
the pointers as iterators...
|
by: richard.forrest1 |
last post by:
I have a problem with an abstract interface class whose implementation
classes need to return different iterator types (but with the same
value_types etc).
Classes A and B both conform to the same abstract Interface class. Interface
has a pair of virtual functions begin() and end() that generate a typical
STL style range. Classes A and B provide different implementations, maybe
using different types of container. The problem is that, to...
|
by: Alvin |
last post by:
Will it be possible to have more than one Iterator in a type?
|
by: Kamen Yotov |
last post by:
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?
| |
by: Jiri Kripac |
last post by:
Languages such as Simula 67 contain a general concept of coroutines that
allow the execution of a method to be suspended without rolling back the
stack and then later resumed at the same place as it has been suspended.
The C# iterators seem to be a special case of this general suspend/resume
concept. The "yield" statement suspends the execution of the current method
and calling MoveNext() resumes it.
I think it would be cleaner to...
|
by: Andrew Matthews |
last post by:
Hi All,
I have the following little class of iterators that allow me to iterate over
elements in the file system. I have nested some of them, and then added Func<FileInfo,
booldelegates to filter out unwanted files. I get an InvalidProgramException
and haven't (yet) been able to find out what's going on. Do you have any
ideas?
TIA
Andrew Matthews
|
by: gexarchakos |
last post by:
Hi there,
Please give me at least a hint...
I have a problem implementing a function object with parameters two
iterators. That is:
A class 'node' produces messages using a routing policy. The routing
policy needs to take the node's neighbours and return a subset of them
based on several criteria. Each message may have different routing
policy. Thus, the policy should be specified while the new message is
|
by: Jess |
last post by:
Hello,
Iterators are typically put into five different categories, namely
input iterator, output iterator, forward iterator, bidirectional
iterator and random iterator. The differences come from the
requirements each kind of iterator has to meet. Therefore, I think
the five categories are kind of conceptual thing, i.e. they are not
really C++ structs/classes etc, is this correct?
There are some functions that return iterators. For...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |