Monday 22 January 2018

enumeration - Iterate Between Enum Values in C#













Suppose
that i have an enumeration like
that:



public enum
Cars
{
Audi = 0,
BMW,

Opel,

Renault,
Fiat,
Citroen,

AlfaRomeo,
}


Do
i have a chance to iterate between Opel and Citroen? I want to give these values as
parameters of a method.


itemprop="text">
class="normal">Answer



This will
work:




for(Cars
car=Cars.Opel; car<=Cars.Citroen; car++)
{

Console.WriteLine(car);
}


but
you have to make sure that the start value is less than the end
value.



EDIT />If you don't hardcode the start and end, but supply them as parameters, you need to
use them in the correct order. If you just switch "Opel" and "Citroen", you will get no
output.




Also (as remarked in the
comments) the underlying integer values must not contain gaps or overlaps. Luckily if
you do not specify values yourself (even the '=0' is not needed), this will be the
default behaviour. See href="http://msdn.microsoft.com/en-us/library/cc138362.aspx"
rel="noreferrer">MSDN:





When you do not specify values for the elements in the enumerator list, the
values are automatically incremented by
1.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...