473,773 Members | 2,286 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 1880
"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
5551
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
2000
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. interface IFoo{} class Foo:IFoo{} class FooBar:IFoo{}
1
3408
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 will give me the file type of a given file? I would prefer not using PInvoke and GetFileVersionInfo,...
104
7202
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..10, 30..100) { } // from 1 to 10 and 30 to hundred
1
1255
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 a callback delegate to make a threadsafe access.
5
2765
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
4253
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 set there values to null and remove them afterwards? Thanks, Jon
21
3643
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 that Unions in C are not typesafe. Now, how is it possible to violate type safety in Unions? ...
4
6341
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 foreach() in /home/mattehz/public_html/acssr/trunk/inc_error.php on line 92
0
9454
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,...
0
10264
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10039
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,...
0
6717
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5355
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...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4012
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2852
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.