473,562 Members | 2,571 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

foreach type unsafe

/* foreach does implicit type conversion on elements of a params argument or
Generic.List.
* This is not good.
* Examples of evil follow...
*/

using System;

// I love it when C# is strict with me...
using System.Collecti ons.Generic;
// ...prettier than C++ templates, not slutty like ArrayList.

namespace DoubleUtilities
{
public static class MaxDouble
{
public static double Max(params double[] list)
{
if (list.Length == 0)
return 0.0D;
double m = list[0];
for (int i = 1; i < list.Length; i++)
{
// Taste the whip of love not given lightly...
//int d = list[i]; //Type error reported (double to int
conversion).
double d = list[i]; // The correct type declaration.

if (d > m)
m = d;
}
return m;
}

public static double MadMax(params double[] list)
{
if (list.Length == 0)
return 0.0D;
double m = list[0];
// Her FOG, her amphetamine, and her pearls...
// And she BREAKS just like a LITTLE GIRL
foreach (int d in list) //Type error unreported (double to int
conversion).
if (d > m)
m = d;
return m;
}
//_______________ _______________ _______________ _______________ ______________
public static double Max(List<double > list)
{
if (list.Count == 0)
return 0.0D;
double m = list[0];
for (int i = 1; i < list.Count; i++)
{
// Taste the whip of love not given lightly...
//int d = list[i]; //Type error reported (double to int
conversion).
double d = list[i]; // The correct type declaration.

if (d > m)
m = d;
}
return m;
}

public static double MadMax(List<dou ble> list)
{
if (list.Count == 0)
return 0.0D;
double m = list[0];

// Her FOG, her amphetamine, and her pearls...
// And she BREAKS just like a LITTLE GIRL
foreach (int d in list) //Type error unreported (double to int
conversion).
if (d > m)
m = d;
return m;
}
//_______________ _______________ _______________ _______________ _______
public static void TestCases()
{
double expected_max = 8.345;
double[] array = { -3.6, 1.1, -2.2, 3.4, 6.6, expected_max, 7.2 };
TestMaxes(array , expected_max);
}

private static void TestMaxes( double[] parameters, double
expected_max )
{
/* Output
parameters={-3.6, 1.1, -2.2, 3.4, 6.6, 8.345, 7.2}
Max( parms double[] list): max=8.345, is_ok=True
Max( List<double> list): max=8.345, is_ok=True
MadMax( parms double[] list): max=8, is_ok=False
MadMax( List<double> list): max=8, is_ok=False
*/
string delimiter = String.Empty;
Console.Write(" parameters={");
for (int i = 0; i < parameters.Leng th; i++)
{
Console.Write(" {0}{1}",delimit er, parameters[i].ToString());
delimiter = ", ";
}
Console.WriteLi ne("}");

double max = Max(parameters) ;
bool is_ok = Math.Abs(max - expected_max) < 1E-12D; //paranoid
double comparison
Console.WriteLi ne("Max( parms double[] list): max={0},
is_ok={1}", max, is_ok);

List<double> list = new List<double>(pa rameters);
max = Max(list);
is_ok = Math.Abs(max - expected_max) < 1E-12D;
Console.WriteLi ne("Max( List<double> list): max={0}, is_ok={1}",
max, is_ok);

max = MadMax(paramete rs);
is_ok = Math.Abs(max - expected_max) < 1E-12D;
Console.WriteLi ne("MadMax( parms double[] list): max={0},
is_ok={1}", max, is_ok);

max = MadMax(list);
is_ok = Math.Abs(max - expected_max) < 1E-12D;
Console.WriteLi ne("MadMax( List<double> list): max={0},
is_ok={1}", max, is_ok);
}
}
}

Jan 15 '06 #1
3 1874
"pg********@blu eyonder.co.uk"
<pg********@blu eyonder.co.uk@d iscussions.micr osoft.com> wrote in message
news:AE******** *************** ***********@mic rosoft.com...
/* foreach does implicit type conversion on elements of a params argument
or
Generic.List.
* This is not good.
* Examples of evil follow...
*/


That's just the way it is, not much you can do about it except not use for
each.

Michael
Jan 15 '06 #2
"Michael C" wrote:
That's just the way it is, not much you can do about it except not use for
each.


That's a pity: foreach has a nice uncluttered syntax.
I guess it is that way for historical reasons - I'd imagine it was those old
untyped collection classes that influenced the semantics of foreach.

You don't suppose that discussions in this group about holes in the type
system might influence the compiler writers to fix those holes, or at least
issue a warning?
Or is that too Pollyanna-ish of me?
Jan 16 '06 #3

"Paul Connolly" <Paul Co******@discus sions.microsoft .com> wrote in message
news:F1******** *************** ***********@mic rosoft.com...
"Michael C" wrote:
That's just the way it is, not much you can do about it except not use
for
each.
That's a pity: foreach has a nice uncluttered syntax.
I guess it is that way for historical reasons - I'd imagine it was those
old
untyped collection classes that influenced the semantics of foreach.

You don't suppose that discussions in this group about holes in the type
system might influence the compiler writers to fix those holes, or at
least
issue a warning?
Or is that too Pollyanna-ish of me?


It is unlikely, I don't know that anyone even bothers monitoring this group.
But I do agree a warning should be there in this case.

Have you looked to see if there is a suggestion at the product feedback
center yet?
http://lab.msdn.microsoft.com/produc...k/default.aspx

Jan 16 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
5542
by: Phil | last post by:
Hi, I read somewhere that the new version (v1.1) has improved the performance of 'foreach' over 'for'. Is that true? I did some measurements and I still think for has an upperhand... ? Phil
13
1982
by: cody | last post by:
foreach does implicitly cast every object in the collection to the specified taget type without warning. Without generics this behaviour had the advantage of less typing for us since casting was neccessary in nearly every collection. But with generics I consider this feature of foreach as dangerous. Casting is now almost always unwanted. ...
1
3398
by: Pierre Drapeau | last post by:
I am looking at a way to get the file type of a given file. The Windows API has GetFileVersionInfo which will retreive that info, burried into a structure. I tried to find the equivalent in C# and found System.Diagnostics.FileVersionInfo. I see that the class has pretty much all the information but the file type. Is there another class that...
104
7082
by: cody | last post by:
What about an enhancement of foreach loops which allows a syntax like that: foeach(int i in 1..10) { } // forward foeach(int i in 99..2) { } // backwards foeach(char c in 'a'..'z') { } // chars foeach(Color c in Red..Blue) { } // using enums It should work with all integral datatypes. Maybe we can step a bit further: foeach(int i in...
1
1247
by: Gustyn | last post by:
I have line of code that was originally written prior to .NET 2.0 as follows: Foreach int i in Items. The problem is it keeps throughing an exception about unsafe thread access. I have read how to fix this using the check to InvokeRequired property but am trying to figure how to apply it when using the foreach command since I have to use...
5
2744
by: james | last post by:
Hey Guys, Would anyone mind explaining why a foreach will implicitly do unsafe casts, and if there is a way to turn this off? Here is an example: ulong vals = new ulong { ulong.MaxValue }; foreach (uint x in vals) Console.WriteLine(x);
29
4209
by: Jon Slaughter | last post by:
Is it safe to remove elements from an array that foreach is working on? (normally this is not the case but not sure in php) If so is there an efficient way to handle it? (I could add the indexes to a temp array and delete afterwards if necessary but since I'm actually working in a nested situation this could get a little messy. I guess I could...
21
3577
by: Chad | last post by:
Okay, so like recently the whole idea of using a Union in C finally sunk into my skull. Seriously, I think it probably took me 2 years to catch on what a Union really is. Belated, I mentioned this too my ultra smart friend who just quit working as a CTO of a wireless company so he go complete his PhD in particle physics. Anyhow he mentioned...
4
6286
by: mattehz | last post by:
Hey there, I am trying to upload old source files and came across these errors: Warning: Invalid argument supplied for foreach() in /home/mattehz/public_html/acssr/trunk/inc_html.php on line 59 Notice: Undefined index: args in /home/mattehz/public_html/acssr/trunk/inc_error.php on line 92 Warning: Invalid argument supplied for...
0
7579
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...
0
8101
jinu1996
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...
1
7630
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...
0
6228
agi2029
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...
1
5479
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5198
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3626
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...
1
1192
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
907
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.