473,320 Members | 2,110 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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.Collections.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<double> 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.Length; i++)
{
Console.Write("{0}{1}",delimiter, parameters[i].ToString());
delimiter = ", ";
}
Console.WriteLine("}");

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

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

max = MadMax(parameters);
is_ok = Math.Abs(max - expected_max) < 1E-12D;
Console.WriteLine("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.WriteLine("MadMax( List<double> list): max={0},
is_ok={1}", max, is_ok);
}
}
}

Jan 15 '06 #1
3 1859
"pg********@blueyonder.co.uk"
<pg********@blueyonder.co.uk@discussions.microsoft .com> wrote in message
news:AE**********************************@microsof t.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******@discussions.microsoft.com> wrote in message
news:F1**********************************@microsof t.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
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
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...
1
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...
104
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...
1
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...
5
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 };...
29
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...
21
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...
4
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...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.