As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I decided to learn some Python (IronPython) syntax today. In doing so, I was impressed by a construct that it allows with its loops.
Python supports an else clause on its loops. An else on a loop basically says, "if this loop finished normally, then enter this clause".
Allow me to demonstrate using C#.
This code:
Something something = SomeCallToSetThisUp();
bool isCompatable = false;
foreach (Widget widget in widgets)
{
isCompatable = widget.IsCompatableWithSomething(something);
if (!isCompatable)
break;
}
if (isCompatable)
compatableSomethings.Add(something);
could become this code (not valid C#):
Something something = SomeCallToSetThisUp();
foreach (Widget widget in widgets)
{
if (!widget.IsCompatableWithSomething(something));
break;
}
else
compatableSomethings.Add(something);
Having never seen this, it struck me as cool. And once you learn it, it seemed as readable as any code I have seen.
While not universally needed (sometimes you want to affect every item in the list), I do think that it would be useful.
So, my question is: Why isn't this in C#?
I have a few ideas why:
break can make debugging harder, so the designers did not want to encourage it.
Not everything that is shiny can make it into the language. (limited scope).
But those are just guesses. I am asking for an actual canonical reason.
The usual answer is because no-one asked for it or the cost of developing and maintaining it outweights the benefits.
From Eric Lippert's blog:
I've already linked several times to Eric Gunnerson's great post on
the C# design process. The two most important points in Eric's post
are: (1) this is not a subtractive process; we don't start with C++ or
Java or Haskell and then decide whether to leave some feature of them
out. And (2) just being a good feature is not enough. Features have to
be so compelling that they are worth the enormous dollar costs of
designing, implementing, testing, documenting and shipping the
feature. They have to be worth the cost of complicating the language
and making it more difficult to design other features in the future.
After we finished the last-minute minor redesigns of various parts of
C# 3.0, we made a list of every feature we could think of that could
possibly go into a future version of C#. We spent many, many hours
going through each feature on that list, trying to "bucket" it. Each
feature got put into a unique bucket. The buckets were labelled:
Pri 1: Must have in the next version
Pri 2: Should have in the next version
Pri 3: Nice to have in the next version
Pri 4: Likely requires deep study for many years before we can do it
Pri 5: Bad idea
Obviously we immediately stopped considering the fours and fives in
the context of the next version. We then added up the costs of the
features in the first three buckets, compared them against the design,
implementation, testing and documenting resources we had available.
The costs were massively higher than the resources available, so we
cut everything in bucket 2 and 3, and about half of what was in bucket
1. Turns out that some of those "must haves" were actually "should haves".
Understanding this bucketing process will help when I talk about some
of the features suggested in that long forum topic. Many of the
features suggested were perfectly good, but fell into bucket 3. They
didn't make up the 100 point deficit, they just weren't compelling
enough.
http://blogs.msdn.com/b/ericlippert/archive/2008/10/08/the-future-of-c-part-one.aspx
Additionally, you need to weight if the feature will be easily understood by existing / new developers. IMHO else on loop is not very readable, especially since the keyword for 'execute this block if the previous one finished OK' is finally.
What is more, I think Enumerable.Any / Enumerable.All methods are much better in this scenarios.
Looping through a collection and checking a condition are different things, so they should be separate language constructs.
Because for else loops are a hack from languages like python. If you feel like you need a for else loop, you should probably put that code in a separate function.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
private void button1_Click(object sender, System.EventArgs e)
{
Clipboard.SetDataObject(textBox1.Text,true);
}
private void button2_Click(object sender, System.EventArgs e)
{
if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
textBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
else
textBox1.Text = "The clipboad does not contain any text";
}
I write this application using C# Windows Form Application
Let's talk for a second about patterns and cults.
You hear a lot about "learn design patterns" and "you suck if you don't use design patterns" and "you should use the X pattern" and all that. There's a whole patterns movement going on...a cult, even...encouraging people to patternify everything. Saying that this is how people ought to do things. That there's a pattern for everything, and by $DEITY, you should be using it.
Guess what? About 80% of it is crap. They're vastly overemphasizing the role and scope of design patterns.
Patterns are a tool. Nothing more. They are not their own reason to exist. They are not the key to world peace. They are not the solution to all problems, and you should not use them just because they are there, or because you drank the cultists' Kool-Aid. You should use them only when and because they are meant for the job you need to do, and they thus make sense.
Design patterns' entire purpose -- their only purpose -- is to reduce overall complexity.* Wherever they do not do that, they are not a good fit, and you should ignore them.
So every time you're thinking about using some particular pattern, ask yourself the one most important question: How will it simplify things?
* Note, i said overall complexity. Applying a design pattern often involves adding complexity to one part of the app in order to remove much more of it from some other part. As long as there's a net loss of complexity, the pattern's still worth looking at.
Now, as for your code.
You've asked about changing that little snippet around to use the Command pattern. I suppose it's possible; i see "copy" and "paste" actions, which could conceivably be parameterized with a reference to the text box.
Question is, though: How will it simplify things?
Without any context other than that snippet, i don't see how you'd gain from adding CopyCommand and PasteCommand classes, and code to instantiate and use them in precisely one place. Perhaps when you're doing lots of copying and pasting in other places, it might be worth it...but right now, no. It feels like you're trying to shoehorn a pattern in where it doesn't want to go.
What is the Correct way of write this using command design pattern?
First, read and understand what cHao wrote in his Answer. (He is not saying that design patterns are crap. He is saying that the way a lot of people use and talk about using design patterns is crap. I agree ...)
Your question doesn't have a good answer:
First, you need to ask yourself why you are trying to use any design pattern at all here. If you are just doing it because you've been told that using design patterns is a good thing, you are doing it for the wrong reason.
Second, repeat that question replacing "any design pattern at all" with "the Command design pattern" ... What are you trying to achieve here by applying this particular design pattern? If you can't answer that, then you need to 1) go back and review the Command design pattern, and understand what it achieves, and 2) then decide whether you actually need what it achieves in your program.
If I was to directly answer your initial and follow-up questions, I would have to say:
the example code snippet doesn't appear to use the Command design pattern,
without seeing the rest of your code, I cannot say whether it should be using that design pattern at all, and
without seeing the rest of your code, I cannot say how it should use that design pattern.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I've just read this page http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx
One of the things they did was to convert the arabic date to the arabic calendar. I'm wondering if it is a good idea at all to do so. Will it actually be annoying/confusing for the user (even if the user is Arabic).
Also, my second question is that do we really need to change 3,899.99 to 3.899,99 for some cultures like German? I mean it doesn't hurt to do so since the library already does it for us but wouldn't this actually cause more confusion to the user (even if he is German).
I'm sure whatever culture these people come from, if i give you a number 3,899.99 there's no way you'd get that wrong right? (since he'd probably learned the universal format anyway)
Your problem here seems to be a bad assumption. There is no "universal format" for numbers. 3,899.99 is valid in some places, and confusing in others. Same for the converse. People can often figure out what they need to (especially if it's in software that is clearly doing a shoddy job of localization otherwise. :) ), but that's not the point.
Except in certain scientific and technical domains that general software doesn't usually address, there's no universal format for any of these things. If you want your software to be accepted on native terms anywhere but your own place, you'll need to work for it.
To me it seems like it would be much less confusing to see dates and numbers in the format you're used to (in your country or language) - why do you think it would be the other way around?
The point of localization is to make your application look more natural for the user. It is definitely advisable to do this in your application if you use it internationally. While you can use US standards, that is not very customer-friendly way of doing things.
How would it be more confusing to a person to see the format they are familiar with? Meet people where they are with your application. If their standard is 10.000,00 and you are showing them 10,000.00, even if they understand it, it does make it a bit disconcerting. Reverse the situation and think what you would like. Would you like a developer using 10.000,00 for their application because you can understand it just fine?
Depends. 3.899,99 to me looks like two numbers. 3.899 and 99. I imagine our number formatting looks similarly funny to foreigners. Sure, I could guess what it means here, but what if you had a whole bunch of numbers like this clustered together? The winning lotto numbers are 45,26,21,56,94,13. Is that one big number, or 6 2-digit numbers?
Date formatting is especially important. 01/02/03. Is that Jan 2 2003, Feb 1 2003, Feb 3 2001 or what? Different cultures specify the d/m/y in different orders. Also, when spelled out, they obviously have different names for the months.
If you have the time and resources to internationalize it, I think you should.
As a foreigner myself, I can assure you that localization helps a lot in terms of user satisfaction. Commas or dots in numbers may induce big mistakes. Another on is the relative position of days and months.
To improve even further, create translations and add an option to choose locale. That way you will have close to 100% customer satisfaction
another important thing is input. if you don't have localization, take the user input "1.234"... what does the user mean? 1.234 or 1234 ? ... there may be users that don't like their values to be off by factor 1000 ... who knows? ;)
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Here is an example of the type of article I'm talking about:
http://support.microsoft.com/kb/319401
I assume these articles are written by people who work for Microsoft and that the code in the articles will always be rock solid and never contain any malicious code. I just want to make sure I can explain to my boss that this is an ok place to copy code from (I've been told never to copy code from the internet, but this seems like a safe source).
I would trust them not to be malicious, but they're not always good code. (MSDN samples are sometimes pretty awful.)
For example, here's some code in the sample you gave:
compareResult = ObjectCompare.Compare
(listviewX.SubItems[ColumnToSort].Text,
listviewY.SubItems[ColumnToSort].Text);
// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
{
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending)
{
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
}
else
{
// Return '0' to indicate they are equal
return 0;
}
Now, there are two issues here:
Why is it deemed valid to have a comparer with no sort order? This should be a constructor parameter, validated at the point of construction IMO.
You should not just negate the result of one comparison to perform a "reverse comparison". That breaks if the result of the first comparison is int.MinValue - because -int.MinValue == int.MinValue. It's better to reverse the arguments used to perform the original comparison.
There are other things I'd take issue with in this code, but these two should be enough to make my point.
I heartily agree with the other answers too, in terms of:
- Check the copyright / licence etc of any code you want to use
- Make sure you understand anything you want to use
Your boss probably wouldn't mind if you only copied the code into a test project that you use to test and understand the code. You can then use what you've learned to write the production code.
And while I don't think anyone outside of Microsoft knows the names of the people who write those support articles, they come from the same vendor that your toolchain does, so if you don't trust the support articles, then you can't trust the tools you've bought either.
Microsoft Knowledgebase articles show safe (as in non-malicious but not necessarily secure) code, but usually the example provides the most basic use case possible. There's a good chance that you'll have to tweak the code a bit for it to work the way you want.
You should also pay attention to the date of the articles. For example, the article you link to is almost three years old. There's definitely a better way to handle that situation now.
Be aware that most codes in articles are there to help you understand the concepts. They are not "production ready". Learn the concepts instead and implement your own.
Have you been told not to copy code from the internet because of rights issues? If so then you don't have to worry about this Microsoft code.
I would advise you not to use any code you don't understand. If you can't say if the code is malicious or not don't use it.
MSDN and kb support articles are written by MS employees that are part of the given product's UX team (user experience). These are people who typically have a background in technical writing, but are not necessarily developers themselves (although some are). It's very common for the UX team to collaborate with developers on the product to ensure their code samples are correct. However this collaboration in my experience is one of the lowest priorities a typical MS developer has and can go ignored, and so it can at times lead to poor code getting out.
With that said, I completely agree with Carl Norum's comment. Copying code you do not understand is done at your own risk. Make sure you understand any code you place in your product!
I've always found the Microsoft articles to be of the highest quality (sadly not their products).
However, there's always the danger of a spoofing site.
Explain that you carefully read the article to understand the information in there, and only copy code that you understand.
If you don't understand the code, then even if the code is correct it may not be doing what you actually need done, thus your program will be incorrect.
You also will have a hard time debugging and maintaining code if there are parts that you don't understand.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm searching for code in c# that can kill computer performance (CPU performance, maybe cpu - memory link performance too) as much as it is possible (it will run on 4 core box so I'm going to create 4 threads and run it simultaneously).
Should it work on int / double / numeric data type / should it have some crazy data structures (but it should not take too much memory) .
Do you have any suggestions ?
Calculate PI using all processors.
You could use parallel Linq to generate a Mandelbrot (Jon Skeet has the code readily available).
Have a program that writes copies of its executable to the drive multiple times for each thread. Have each of these copies of the program then triggered by the program. :)
If you want to kill a machine's performance, try hitting the disk, because IO interrupts tend to affect everything even on a good CPU scheduler. Something like enumerating a directory of many little files, or writing a lot of big files to disk would do the trick.
Why re-invent the wheel? Use existing Load Testing software.
Calculate a long sequence of prime numbers. The following link contains code that can be modified to do this..
Program to find prime numbers
Call Bitmap.GetPixel, in a loop, in an image processing application.
I would say: a naieve (brute force) travelling salesman implementation:
(from wikipedia):
The Travelling Salesman Problem (TSP) is an NP-hard problem in combinatorial optimization studied in operations research and theoretical computer science. Given a list of cities and their pairwise distances, the task is to find a shortest possible tour that visits each city exactly once.
Brute force solving of N Queens (see wikipedia) for for example 64 queens.
Because a simple loop like this can be optimized away (sometimes only after a few minutes already running):
while(true) {
i++;
}
You can, as well, resolve a very long encrypted message, encrypted by a key such as 2048 bits.
That's a killer.
An open-source, multithreaded 3D modeling program rendering an extremely complex lighted scene will pound the strongest system into submission.
Okay, how about some infinite recursion in the spirit of StackOverflow?
void deathToAllRobots(int someMeaninglessValue) {
deathToAllRobots(someMeaninglessValue+1);
}
int *x;
while(1)
{
x = new int[10];
}
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
You'd think both are the same.
But maybe it's the compiler that Microsoft has used, but I've noticed that when compiling two very small programs, identical logic. VB.NET uses more IL instructions.
Is it true than that c# must be faster, if only because its compiler is smarter.
This is really hard to respond to definitively with the limited amount of information available. It would help a lot if you provided the code from both samples and the compiler options used.
To answer the question though, no C# is not inherently faster. Both languages generate to IL and run on the CLR. For most features they even generate the same IL. There are differences for some similar features but they rarely add up to significant performance changes.
VB can appear slower if you run into some of the subtle differences in the languages and environment. A couple of common examples are ...
Many environments default to checked integer operations for VB.Net but not C#
Subtle coding issues can lead to late binding where it appears to be early binding
Believing switch and Select have the same semantics
Once these are removed the languages perform with very similar performance profiles.
The answer is yes and no. It really depends on what specific feature you are referring to. Likewise, there are areas where VB executes faster. I can give an example of each.
This code in VB...
For i As Integer = 0 To Convert.ToInt32(Math.Pow(10, 8))
Next
...is about 100x faster than this code in C#.
for (int i = 0; i <= Convert.ToInt32(Math.Pow(10, 8)); i++)
{
}
It is not that the VB compiler is better at generating code that executes for loops faster though. It is that VB computes the loop bound once while C# computes the loop condition on each iteration. It is just a fundamental difference in the way the languages were intended to be used.
This code is C#...
int value = 0;
for (int i = 0; i <= NUM_ITERATIONS; i++)
{
value += 1;
}
...is slightly faster than the equivalent in VB.
Dim value As Integer = 0
For i As Integer = 0 To NUM_ITERATIONS
value += 1
Next
The reason in this case is that the default behavior for VB is to perform overflow checking while C# does not.
I am sure there are other difference in the languages that demonstrate similiar performance biases. But, both languages are built on top of the CLR and both compile to the same IL. So making blanket statements like "Language X is faster than language Y" without adding the important qualifying "in situation Z" clause are simply incorrect.
C# match more close to IL than VB.NET
VB.NET sometimes do lot of things behind the scenes. Like On Error Resume Next, that write a try catch for each statement
But in general both have the same features and performance.
You can open your code in Reflector and see as C# code. Realize if C# code was what you expected
Make sure the programs really are identical. For example, depending on Options, these two lines are actually very different:
Dim x = "some string"
.
string x = "some string";
To match that C# code, the VB should look like this:
Dim x As String = "some string"
It sounds like the differences are purely in the compilers interpretation of the source code. A tech republic article comes to pretty much the same conclusion:
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1027686.html
I haven't done any tests, but I think speed would be about the same. If anything select for coding style and syntax.