Tuesday, December 29, 2009

Hanging Pictures

I got some pictures from Salvation Army on Monday, and decided to hang them today. Thinking there must be design and aesthetic principles for hanging pictures, besides which way is up, I did a google search on the web.

Here's an excellent site:


Monday, December 28, 2009

Kung Fu

I'm watching "Kung Fu" reruns ... if you're wanted and there are posters with "Kwai Chang Caine -- $10,000" all over the place ... why don't you change your name?

You can't have it both ways -- if everyone is a redneck bigot -- shouldn't Kwai Chang Caine look like every other "Chinaman"? How come even the most backwards hick can recognize long haired western clothed Caine in a hat as the bald-headed robe-garbed monk in a rather poor sketch? (Granted the tattoos sometimes are the giveaway).

Tuesday, December 22, 2009

Glucose conversion

I was looking online for conversion between American and Canadian units as my mental model for insulin coverage is in American units, but my meter is in Canadian units.

But I don't want an online app! I just want a simple chart that's easy to read on my cellphone - I can message it there and look it up anytime.

First I got a text chart that was impossible to read on my cellphone. Multiple cols, laid out so that you don't have to scroll. The issue is not scrolling - easy to do on a blackberry - it's trying to decide whether the one number is associated with the one on it's left or the one on it's right when the separators are "---".

Next I looked at an online app -- but connecting/getting a link is SLOW...

So I made up my own chart - dead simple. Paste it into a message, send it to your cellphone, and watch your diet and exercise!

American Canadian
mg% mmol/l
20 1.1
30 1.7
40 2.2
50 2.8
55 3.1
60 3.3
65 3.6
70 3.9
75 4.2
80 4.4
85 4.7
90 5
95 5.3
100 5.6
105 5.8
110 6.1
115 6.4
120 6.7
125 6.9
130 7.2
135 7.5
140 7.8
145 8.1
150 8.3
155 8.6
160 8.9
165 9.2
170 9.4
175 9.7
180 10
185 10.3
190 10.6
195 10.8
200 11.1
205 11.4
210 11.7
215 11.9
220 12.2
225 12.5
230 12.8
235 13.1
240 13.3
245 13.6
250 13.9
255 14.2
260 14.4
265 14.7
270 15
275 15.3
280 15.6
285 15.8
290 16.1
295 16.4
300 16.7
310 17.2
320 17.8
330 18.3
340 18.9
350 19.4
360 20
370 20.6
380 21.1
390 21.7
400 22.2
410 22.8
420 23.3
430 23.9
440 24.4
460 25.6
480 26.7
500 27.8
520 28.9
540 30
560 31.1
580 32.2
600 33.3

Monday, December 14, 2009

What Great .NET Developers Ought To Know (More .NET Interview Questions)


Calling Lisp from C or C++

Here's a link on how to do this ...


Sunday, December 6, 2009

DataGridView not updating in c#

How to update a DataGridView in c#.

I found that a DataGridView does not seem to update correctly when the DataSource is changed.

Theoretically, the following two pieces of code should be equivalent, where OutputGridView is a DataGridView, and myList is a list of objects to be displayed:

Code 1:

OutputDataGridView.DataSource = myList;
Code 2:

OutputDataGridView.DataSource = null;
OutputDataGridView.DataSource = myList;

Given normal program semantics, the two pieces of code should be equivalent. The only way they cannot be equivalent if assignment (or specifically assignment to null) has side effects that change the semantics. This must be the case, because in y program changing the code from code 1 to code 2 changes the behavior.

And yes, I did google for solutions, the DataGridView Program Manager suggested adding


but this did not fix the problem.

Hope that this may help someone else!

Saturday, September 12, 2009

Hidden Features of C#

Posted on stackoverflow.com: http://stackoverflow.com/questions/9033/hidden-features-of-c

Larry Watanabe 1,540●3●13 logout about faq

Ask Question
Hidden Features of C#
This came to my mind after I learned the following from this question:where T : struct
We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.
Some of us even mastered the stuff like Generics, anonymous types, lambdas, linq, ...
But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?
Here are the revealed features so far:
yield by Michael Stumvar by Michael Stumusing() statement by kokosreadonly by kokosas by Mike Stoneas / is by Ed Swangrenas / is (improved) by Rocketpantsdefault by deathofratsglobal:: by pzycomanusing() blocks by AlexCusevolatile by Jakub Šturcextern alias by Jakub Šturc
DefaultValue by Michael StumObsoleteAttribute by DannySmurfDebuggerDisplayAttribute by StuDebuggerBrowsable and DebuggerStepThrough by bdukesThreadStaticAttribute by marxidadFlagsAttribute by Martin ClarkeConditionalAttribute by AndrewBurns
?? operator by kokosnumber flaggings by Nick Berardiwhere T:new by Lars Mæhlumimplicit generics by Keithone-parameter lambdas by Keithauto properties by Keithnamespace aliases by Keithverbatim string literals with @ by Patrickenum values by lfoust@variablenames by marxidadevent operators by marxidadformat string brackets by Portmanproperty accessor accessibility modifiers by xanadontternary operator (?:) by JasonSchecked and unchecked operators by Binoj Antonyimplicit and explicit operators by Flory
Language Features
Nullable types by Brad BarkerCurrying by Brian Leahyanonymous types by Keith__makeref __reftype __refvalue by Judah Himangoobject initializers by lomaxxformat strings by David in DakotaExtension Methods by marxidadpartial methods by Jon Ericksonpreprocessor directives by John AsbeckDEBUG pre-processor directive by Robert Durginoperator overloading by SefBkntype inferrence by chakritboolean operators taken to next level by Rob Gough
Visual Studio Features
snippets by DannySmurf
TransactionScope by KiwiBastardDependantTransaction by KiwiBastardNullable by IainMHMutex by DiagoSystem.IO.Path by ageektrappedWeakReference by Juan Manuel
Methods and Properties
String.IsNullOrEmpty() method by KiwiBastardList.ForEach() method by KiwiBastardBeginInvoke(), EndInvoke() methods by Will DeanNullable.HasValue and Nullable.Value properties by RismoGetValueOrDefault method by John Sheehan
Tips & Tricks
nice method for event handlers by Andreas H.R. Nilssonuppercase comparisons by Johnaccess anonymous types without reflection by dpa quick way to lazily instantiate collection properties by WillJavaScript-like anonymous inline-functions by roosteronacid
netmodules by kokosLINQBridge by Duncan SmartParallel Extensions by Joel Coehoorn

edited Sep 9 at 11:35

community wiki
34 revisions, 17 usersSerhat Özgel 16%

--overloading the "true" operator.. --overloading the true and binary operators to simulate overloading the boolean operators (&& ).. – therealhoff Sep 18 '08 at 23:16

Some of those links simply take you to the top of the question itself and not to the specific answers. You might want to think about fixing them. (175 answers (as of this writing) is a lot to search through.) – RobH May 8 at 18:23
add / show 13 more comments

232 Answers
oldest newest votes
1 2 3 4 58 next
This isn't C# per se, but I haven't seen anyone who really uses System.IO.Path.Combine() to the extent that they should. In fact, the whole Path class is really useful, but no one uses it!
I'm willing to bet that every production app has the following code, even though it shouldn't:string path = dir + "\\" + fileName;
answered Aug 13 '08 at 1:53

community wiki


Everyone should be using Path.Combine()... it's crazy not to. – Jon Tackabury Oct 21 at 18:28

Path.Combine is also essential for cross-platform coding as it uses whatever path separator the current OS uses. – Gary Willoughby Nov 17 at 9:57

Path.Combine( ) is really bad, it doesn't combine paths! Do MessageBox.Show(Path.Combine(@"c:\temp", @"\assembly")); and you will see why. See also dotnet.org.za/hiltong/archive/…tuinstoel Jan 1 at 16:34

@tuinstoel it works for me so far :-) Prefixing a path with a slash should have the same effect as when you execute cd \ in command prompt, it should take you back to the root no matter where you are.... so Path.Combine is working as it should... – chakrit Mar 22 at 10:35

Now if only it would take in a param array of items instead of just two.. – Andy Jun 8 at 15:27
add / show 18 more comments
From Rick Strahl:
You can chain the ?? operator so that you can do a bunch of null comparisons.string result = value1 ?? value2 ?? value3 ?? String.Empty;
edited Aug 27 '08 at 1:34

community wiki
2 revisions

cool !! but don't you think you might mess evrything up ? – Yassir May 8 at 17:27

Nice! Definitely cleaner than 3 if statements! – SkippyFire Jun 5 at 18:12
add / show 1 more comment
Read all the answers but I think lambdas and type inferrence is underrated.
Havn't seen anyone mentioned that Lambdas can have multiple statement and they double as a compatible delegate object automatically (just make sure the signature match) as in:Console.CancelKeyPress += (sender, e) => { Console.WriteLine("CTRL+C detected!\n"); e.Cancel = true; };
Note that I don't have a new CancellationEventHandler nor do I have to specify types of sender and e, they're inferrable from the event. Which is why this is less cumbersome to writing the whole delegate (blah blah) which also requires you to specify types of parameters.
Lambdas don't need to return anything and type inference is extremely powerful in context like this.
and BTW, you can always return Lambdas that make Lambdas in the functional programming sense. For example, here's a lambda that make a lambda that handles a Button.Click event:Func makeHandler = (dx, dy) => (sender, e) => { var btn = (sender as Button); btn.Top += dy; btn.Left += dx; };btnUp.Click += makeHandler(0, -1);btnDown.Click += makeHandler(0, 1);btnLeft.Click += makeHandler(-1, 0);btnRight.Click += makeHandler(1, 0);
Note the chaining: (dx, dy) => (sender, e) =>
Now that's why I'm happy to have taken the functional programming class :-)
Other than the pointers in C, I think its the other fundamental thing you should learn :-)
edited Apr 6 at 12:45

community wiki
4 revisions, 2 users
add / show 6 more comments
From CLR via C#:
When normalizing strings, it is highly recommended that you use ToUpperInvariant instead of ToLowerInvariant because Microsoft has optimized the code for performing uppercase comparisons.
I remember one time my coworker always changed strings to uppercase before comparing. I've always wondered why he does that because I feel it's more "natural" to convert to lowercase first. After reading the book now I know why.
answered Aug 15 '08 at 11:06

community wiki


When you "convert a string to upper case" you create a second temporary string object. I thought that this kind of comparison was not preferred, that the best way was: String.Equals(stringA, stringB, StringComparison.CurrentCultureIgnoreCase) whcih does not create this throwaway string at all. – Anthony Sep 23 '08 at 14:44

What kind of optimization can you perform on comparing upper case strings that can't be done on lower case strings? I don't understand why one would be more optimal than the other. – Parappa Oct 24 at 17:38

Converting to uppercase rather than lowercase can also prevent incorrect behavior in certain cultures. For example, in Turkish, two lowercase i's map to the same uppercase I. Google "turkish i" for more details. – neilwhitaker1 Dec 17 at 17:17

I tried benchmarking ToUpperInvariant vs ToLowerInvariant. I cannot find any difference in their performance under .NET 2.0 or 3.5. Certainly not anything that warrant "highly recommending" using one over the other. – Rasmus Faber Jan 21 at 21:41

ToUpperInvariant is preferred because it makes all characters round-trip. See msdn.microsoft.com/en-us/library/…. For comparisons, write`"a".Equals("A", StringComparison.OrdinalIgnoreCase)` – SLaks Jun 4 at 19:35
add / show 6 more comments
Avoid checking for null event handlers
Adding an empty delegate to events at declaration, suppressing the need to always check the event for null before calling it is awesome. Example:public delegate void MyClickHandler(object sender, string myValue);public event MyClickHandler Click = delegate {}; // add empty delegate!
Let you do thispublic void DoSomething(){ Click(this, "foo");}
Instead of thispublic void DoSomething(){ // Unnecessary! MyClickHandler click = Click; if (click != null) // Unnecessary! { click(this, "foo"); }}
Please also see this related discussion and this blog post by Eric Lippert on this topic (and possible downsides).
edited May 8 at 17:26

community wiki
5 revisions, 4 usersAndreas H.R. Nilsson 77%

I believe a problem will appear if you rely on this technique and then you have to serialize the class. You will eliminate the event, and then on deserialization you will get a NullRefference.... .So one can just stick to the "old way" of doing things. It's safer. – sirrocco Oct 13 '08 at 9:58

you can still set your event handler to null, so you can still get a null reference, and you still have a race condition. – Robert Paulson Oct 19 at 23:00

A quick profile test shows that dummy-subscribed event handler without null test takes roughly 2x the time of unsubscribed event handler with null test. Multicast event handler without null test takes about 3.5x the time of singlecast event handler with null test. – P Daddy Nov 17 at 6:53

This avoids the need for a null check by just always having a self-subscriber. Even as an empty event this carries an overhead that you don't want. If there are no subscribers you don't want to fire the event at all, not always fire an empty dummy event first. I would consider this bad code. – Keith Dec 4 at 14:49

This is a terrible suggestion, for the reasons in the above comments. If you must make your code look "clean", use an extension method to check for null then call the event. Someone with modify privileges should definitely add the cons to this answer. – Greg Mar 31 at 4:29
add / show 16 more comments
I didn't know the "as" keyword for quite a while.MyClass myObject = (MyClass) obj;
vsMyClass myObject = obj as MyClass;
The second will return null if obj isn't a MyClass, rather than throw a class cast exception.
answered Aug 12 '08 at 16:42

Mike Stone
community wiki


Don't over-do it though. Lots of people seem to use as because the prefer the syntax even though they want the semantics of a (ToType)x. – Scott Langham Sep 19 '08 at 18:07

I don't believe it offers better performance. Have you profiled it? (Obviously though it does when the cast fails... but when you use (MyClass) cast, failures are exceptional.. and extremely rare (if they happen at all), so it makes no difference. – Scott Langham Jan 21 at 13:01

This is only more performant if the usual case is the cast failing. Otherwise the direct cast (type)object is faster. It takes longer for a direct cast to throw an exception than to return null though. – Spence Jan 26 at 14:54

Right along the same lines of the "as" keyword... the "is" keyword is just as useful. – dkpatt May 7 at 19:09
add / show 6 more comments
All the above, plus
1) implicit generics (why only on methods and not on classes?)void GenericMethod( T input ) { ... }//infer type, soGenericMethod(23); //you don't need the <>GenericMethod(23); //is enough
2) simple lambdas with one parameter:x => x.ToString() //simplify so many calls
3) anon types and initialisers://duck-typed: works with any .Add methodvar colours = new Dictionary { { "red", "#ff0000" }, { "green", "#00ff00" }, { "blue", "#0000ff" }};int[] arrayOfInt = new { 1, 2, 3, 4, 5 };
Another one:
4) Auto properties can have different scopes:Public int MyId { get; private set; }
Thanks @pzycoman for reminding me:
5) Namespace aliases (not that you're likely to need this particular distinction):using web = System.Web.UI.WebControls;using win = System.Windows.Forms;web::Control aWebControl = new web::Control();win::Control aFormControl = new win::Control();
edited Aug 29 '08 at 16:22

community wiki
5 revisions

i think you've been able to initialize arrays with int[] nums = {1,2,3}; since 1.0 :) doesn't even need the "new" keyword – Lucas Oct 7 '08 at 23:26

also lambda without parameters ()=> DoSomething(); – pablito Jan 12 at 8:38

I've used both { get; internal set; } and { get; protected set; }, so this pattern is consistent. – Keith May 4 at 21:23
add / show 16 more comments
My favorite trick is using the null coalesce operator and parens to automagically instantiate collections for me.private IList _foo;public IList ListOfFoo { get { return _foo ?? (_foo = new List()); } }
edited Aug 18 at 18:18

community wiki
4 revisions

Oh this is cool! I use that idiom all the time in Ruby (everyone does), but had not yet realized that it now maps directly to c#!! – Charlie Flowers Mar 23 at 3:44

Don't you find it hard to read? – Riri May 19 at 18:40

Its slightly hard to read for the noo... er, inexperienced. But its compact and contains a couple patterns and language features that the programmer should know and understand. So, while it is hard at first, it provides the benefit of being a reason to learn. – Will May 20 at 13:23
add / show 10 more comments
aliased generics:using ASimpleName = Dictionary>>;
allows you to use ASimpleName, instead of Dictionary>>
use it when you would use the same generic big long complex thing in a lot of places
answered Sep 16 '08 at 16:53

community wiki


Haha that's kind of cool, but I'm very glad that C# 3 has implemented the "var" keyword which has got rid of some of the ugliness with generic instantiation like: Dictionary>> myDic = new Dictionary>>(); – cbp Nov 26 at 6:36

+1 This was new to me. I used to subclass to death here. – Dave Van den Eynde May 28 at 14:53

Holy .... this one truly made reading this post worthy. 8) – Arnis L. Jun 6 at 19:41
add / show 1 more comment
"yield" would come to my mind. Some of the Attributes like [DefaultValue()] are also among my favorites.
The "var" keyword is a bit more known, but that you can use it in .net 2.0 Applications as well (as long as you use the .net 3.5 Compiler and set it to output 2.0 code) does not seem to be known very well.
Edit: Thanks kokos for pointing out the ?? operator, that's indeed really useful. Since it's a bit hard to google for it (as ?? is just ignored), here is the Documentation Page for that operator: http://msdn.microsoft.com/en-us/library/ms173224.aspx
edited Aug 12 '08 at 16:53

Michael Stum
community wiki
3 revisions

The default value's documentation says it is not really setting the value of the property. It's only a helper for visualisers and code generators. – boris callens Nov 8 at 1:18
add comment
Two things I like are Automatic properties so you can collapse your code down even further:private string _name;public string Name{ get { return _name; } set { _name = value; }}
becomespublic string Name { get; set;}
Also object initializers:Employee emp = new Employee();emp.Name = "John Smith";emp.StartDate = DateTime.Now();
becomesEmployee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()}
answered Aug 13 '08 at 7:39

community wiki


Should it be noted that Automatic Properties are a C# 3.0 only feature? – Jared Updike Sep 18 '08 at 22:53

Automatic Properties were introduced with the 3.0 compiler. But since the compiler can be set to output 2.0 code, they work just fine. Just don't try to compile 2.0 code with automatic properties in an older compiler! – Josh Mar 10 at 14:59

Something many people don't realise is that get and set can have different accessibility, eg: public string Name { get; private set;} – nader Jun 13 at 20:27
add / show 2 more comments
The @ tells the compiler to ignore any escape characters in a string.
just wanted to clarify this one... it doesn't tell it to ignore the escape characters, it actually tells the compiler to interpret the string as a literal.
if you have string s = @"cat dog fish"
it will actually print out as (note that it even includes the whitespace used for indentation)cat dog fish
edited May 8 at 21:18

community wiki
3 revisions, 3 userslomaxx 75%

It would be clearer if the output showed the spaces that would be printed out as well. Right now it seems as if the new lines characters are printed but spaces are ignored. – aleemb Apr 28 at 11:15
add / show 3 more comments
I tend to find that most C# developers don't know about 'nullable' types. Basically, primitives that can have a null value.double? num1 = null; double num2 = num1 ?? -100;
Set a nullable double, num1, to null, then set a regular double, num2, to num1 or -100 if num1 was null.
edited Aug 20 '08 at 14:50

community wiki
2 revisions, 2 users
add / show 8 more comments
Here's a useful one for regular expressions and file paths:"c:\\program files\\oldway"@"c:\program file\newway"
The @ tells the compiler to ignore any escape characters in a string.
edited Aug 12 '08 at 19:01

community wiki
2 revisions

Also, a @ constant accepts newlines inside. Perfect when assigning a multiline script to a string. – Tor Haugen Nov 19 at 16:17
add / show 2 more comments
I think one of the most under-appreciated and lesser-known features of C# (3.5) are Expression Trees, especially when combined with Generics and Lambdas. This is an approach to API creation that newer libraries like NInject and Moq are using.
For example, let's say that I want to register a method with an API and that API needs to get the method name
Given this class:public class MyClass{ public void SomeMethod() { /* Do Something */ }}
Before, it was very common to see developers do this with strings and types (or something else largely string-based):RegisterMethod(typeof(MyClass), "SomeMethod");
Well, that sucks because of the lack of strong-typing. What if I rename "SomeMethod"? Now, in 3.5 however, I can do this in a strongly-typed fashion:RegisterMethod(cl => cl.SomeMethod());
In which the RegisterMethod class uses Expression> like this:void RegisterMethod(Expression> action) where T : class{ var expression = (action.Body as MethodCallExpression); if (expression != null) { // TODO: Register method Console.WriteLine(expression.Method.Name); }}
This is one big reason that I'm in love with Lambdas and Expression Trees right now.
answered Sep 9 '08 at 21:52

community wiki

add / show 1 more comment
The 'default' keyword in generic types:T t = default(T);
results in a 'null' if T is a reference type, and 0 if it is an int, false if it is a boolean, etcetera.
answered Aug 13 '08 at 10:20

community wiki


Cool! I have to remember this! – Dave Van den Eynde May 28 at 14:56
add comment
Unions (the C++ shared memory kind) in pure, safe C#
Without resorting to unsafe mode and pointers, you can have class members share memory space in a class/struct. Given the following class:[StructLayout(LayoutKind.Explicit)]public class A{ [FieldOffset(0)] public byte One; [FieldOffset(1)] public byte Two; [FieldOffset(2)] public byte Three; [FieldOffset(3)] public byte Four; [FieldOffset(0)] public int Int32;}
You can modify the values of the byte fields by manipulating the Int32 field and vice-versa. For example, this program: static void Main(string[] args) { A a = new A { Int32 = int.MaxValue }; Console.WriteLine(a.Int32); Console.WriteLine("{0:X} {1:X} {2:X} {3:X}", a.One, a.Two, a.Three, a.Four); a.Four = 0; a.Three = 0; Console.WriteLine(a.Int32); }
Outputs this:2147483647FF FF FF 7F65535
just add using System.Runtime.InteropServices;
answered Sep 23 '08 at 20:39

community wiki


+1 awesome! This would enables a whole lots of number manipulation tricks from C++ days :-) – chakrit Dec 30 at 18:58

Cool, but I totally would murder someone who I saw doing this. – George Mauer Apr 9 at 19:12
add / show 3 more comments
Attributes in general, but most of all DebuggerDisplay. Saves you years.
edited Apr 26 at 16:34

community wiki
2 revisions, 2 usersboj 56%

Using DebuggerDisplay Attribute (MSDN): msdn.microsoft.com/en-us/library/…Mufasa Sep 26 '08 at 17:14
add / show 2 more comments
Using @ for variable names that are keywords.var @object = new object();var @string = "";var @if = IpsoFacto();
answered Aug 18 '08 at 1:45

Mark Cidade
community wiki


Why would you want to use a keyword as a variable name? Seems to me that this would make code less readable and obfuscated. – Jon Sep 13 '08 at 4:18

Well, the reason that it's there is that CLI requires it for interoperability with other languages that might use C# keywords as member names – Mark Cidade Sep 18 '08 at 22:04

If you ever wanted to use the asp.net MVC HTML helpers and define a HTML class you will be happy to know that you can use @class so it won't be recognised as the class keyword – boris callens Sep 23 '08 at 7:18

This is not a feature, @ is just allowed symbol for naming like _ and many others (name '@this' will not be equal to name 'this') – zihotki Feb 21 at 7:34

@zihotki: Wrong. var a = 5; Console.WriteLine(@a); Prints 5 – SLaks Jun 4 at 17:40
add / show 9 more comments
Not sure why anyone would ever want to use Nullable though. :-)
True, False, FileNotFound?
edited Nov 22 at 7:39

Barry Kelly
community wiki
2 revisions, 2 users

if expect a user to answer a yes no question then null would be appropriate if the question has not been answered – Omar Kooheji Oct 24 at 12:38

Yes, No, Maybee? – Dan Blair May 22 at 20:19

Store values of a ThreeState CheckBox – Shimmy Jul 13 at 15:04
add / show 9 more comments
@Ed, I'm a bit reticent about posting this as it's little more than nitpicking. However, I would point out that in your code sample:MyClass c; if (obj is MyClass) c = obj as MyClass
If you're going to use 'is', why follow it up with a safe cast using 'as'? If you've ascertained that obj is indeed MyClass, a bog-standard cast:c = (MyClass)obj
...is never going to fail.
Similarly, you could just say:MyClass c = obj as MyClass;if(c != null){ ...}
I don't know enough about .NET's innards to be sure, but my instincts tell me that this would cut a maximum of two type casts operations down to a maximum of one. It's hardly likely to break the processing bank either way; personally, I think the latter form looks cleaner too.
answered Aug 12 '08 at 18:03

community wiki


If the cast is to the exact type (cast to "A" when object is "A", not derived from it), the straight cast is ~3x FASTER than "as". When casting a derived type (cast to "A" when object is "B", which derives from "A"), the straight cast is ~0.1x slower than "as". "is", then "as" is just silly. – P Daddy Nov 17 at 7:15
add / show 7 more comments
Returning anonymous types from a method and accessing members without reflection.// Useful? probably not.private void foo(){ var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) }); Console.WriteLine("Name: {0} Badges: {1}", user.Name, user.Badges);}object GetUserTuple(){ return new { Name = "dp", Badges = 5 };} // Using the magic of Type Inference...static T AnonCast(object obj, T type){ return (T) obj;}
answered Aug 17 '08 at 1:01

community wiki


Very nice! I thought the only way to return multiple values was to define a new type. – blackwing Sep 23 '08 at 8:01

That really doesn't get you anything. It is actually dangerous. What if GetUserTuple is modified to return multiple types? The cast will fail at run time. One of the great things about C#/.Net is the compile time checking. It would be much better to just create a new type. – Jason Jackson Sep 30 '08 at 1:10

@Jason I did say it's probably not useful but it is surprising (and I thought hidden). – dp Sep 30 '08 at 14:41

While cool, this seems like a rather poor design choice. You've basically defined the anonymous type in two places. At that point, just declare a real struct and use it directly. – Paul Alexander May 7 at 9:05
add / show 3 more comments
If you want to exit your program without calling any finally blocks or finalizers useEnvironment.FailFast()
answered Oct 13 '08 at 22:25

Jan Bannister
community wiki


Would probably be great for an "Emergency Shutdown" button! – SkippyFire Jun 5 at 18:52

Excellent name for method. :) – Arnis L. Jun 6 at 19:48
add / show 3 more comments
for system independant newlines.
answered Sep 1 '08 at 0:03

community wiki


The annoying thing about this one, is that it isn't included into the compact framework. – Stormenet Dec 8 at 7:21

Its worth pointing out that this is specific to the application's host platform - so if you are creating data intended for another system, you should use \n or \r\n appropriately. – Adrian Jun 2 at 12:04
add comment
Here are some interesting hidden C# features:__makeref__reftype__refvalue
These are undocumented C# keywords (even Visual Studio recognizes them!) that were added to for a more efficient boxing/unboxing prior to generics. They work in coordination with the System.TypedReference struct.
There's also __arglist, which is used for variable length parameter lists.
One thing folks don't know much about is System.WeakReference -- a very useful class that keeps track of an object but still allows the garbage collector to collect it.
The most useful "hidden" feature would be the yield return keyword. It's not really hidden, but a lot of folks don't know about it. LINQ is built atop this; it allows for delay-executed queries by generating a state machine under the hood. Raymond Chen recently posted about the internal, gritty details.
edited Mar 4 at 18:19

Joan Venge
community wiki
2 revisions, 2 usersJudah Himango 76%
add / show 1 more comment
This one is not "hidden" so much as it is misnamed.
A lot of attention is paid to the algorithms "map", "reduce", and "filter". What most people don't realize is that .NET 3.5 added all three of these algorithms, but it gave them very SQL-ish names, based on the fact that they're part of LINQ.
"map" => Select Transforms data from one form into another
"reduce" => Aggregate Aggregates values into a single result
"filter" => Where Filters data based on a criteria
The ability to use LINQ to do inline work on collections that used to take iteration and conditionals can be incredibly valuable. It's worth learning how all the LINQ extension methods can help make your code much more compact and maintainable.
answered Aug 16 '08 at 23:55

Brad Wilson
community wiki

add / show 2 more comments
Maybe not an advanced technique, but one I see all the time that drives me crazy:if (x == 1){ x = 2;}else{ x = 3;}
can be condensed to:x = (x==1) ? 2 : 3;
answered Aug 19 '08 at 15:54

community wiki


I guess because they're not the same things, being an operator not a statement. I prefer the first approach myself. It's more consistent and easily expandable. Operators can't contain statements, so the minute you have to expand the body, you'll have to convert that ternary operator to an if statement – kervin Apr 18 at 16:34

@Guillaume: To account for all values of x: x = 2 + System.Math.Min(1,System.Math.Abs(x-1)); – mbeckish Jun 6 at 20:17

It's actually called the "conditional operator" - it is a ternary operator because it takes three arguments. en.wikipedia.org/wiki/Conditional_operatorBlorgbeard Jun 30 at 9:24
add / show 4 more comments
If you're trying to use brackets inside a String.Format expression...int foo = 3;string bar = "blind mice";String.Format("{{i am in brackets!}} {0} {1}", foo, bar);//outputs "{i am in brackets!} 3 blind mice"
answered Aug 18 '08 at 22:29

community wiki

add comment
?? - great operator
using - great keyword that can be used for more than just calling Dispose
readonly - should be used more
netmodules - too bad there's no support in Visual Studio
edited Aug 12 '08 at 16:39

community wiki
2 revisions

It really sucks that you can't google ?? – Lucas Aardvark Jun 19 at 15:02

@LucasAardvark: As J Steen mentioned it's called the null coalescing operator. Search for that! – kokos Jun 21 at 1:54
add / show 7 more comments
TransactionScope and DependentTransaction in System.Transactions is a lightweight way to use transaction processing in .NET - its not just for Database transactions either
String.IsNullOrEmpty is one that I am surprised to learn a lot of devs don't know about
List.ForEach - iterate through your generic list using a delegate method
There are more, but that is the 3 obvious ones of the top of my head...
edited Aug 17 at 12:41

Dave Markle
community wiki
3 revisions, 3 usersKiwiBastard 67%

Any proof that List.ForEach can be faster than normal loop? – arbiter Jul 17 at 14:43

That List.ForEach is faster than foreach or for(;;) is completely bonkers. ForEach uses a method/function delegate to implement the behavior. This is first of all, means worse cache locality because the code is generally executed further away (in memory) from the actual loop. Secondly all you really need to do to verify that this is slower is to look a the generated native code. There's a lot more stuff going on with List.ForEach than you might think. – John Leidegren Aug 5 at 17:13
add / show 2 more comments
1 2 3 4 58 next
Your Answer
$(function() { editorReady(0); });
Ctrl+B" XShift="0px">
Ctrl+I" XShift="-20px">
Ctrl+L" XShift="-40px">
Ctrl+Q" XShift="-60px">
Ctrl+K" XShift="-80px">
Ctrl+G" XShift="-100px">
Ctrl+O" XShift="-120px">
Ctrl+U" XShift="-140px">
/ Ctrl+H" XShift="-160px">
Ctrl+R" XShift="-180px">

Not the answer you're looking for? Browse other questions tagged or ask your own question.
× 38168 × 89
1 year ago
66,448 times
latest activity

'Wanted: ' +
'' +
"Lead Software Engineer - Web Mining" +
' at ' +
"Untangly, inc.
(" +
"Mountain View, CA" +
'). See this and other great job listings at ' +

Wanted: Lead Software Engineer - Web Mining at Untangly, inc. (Mountain View, CA). See this and other great job listings at jobs.stackoverflow.com.
Hidden Features of Java
Hidden features of Eclipse
Hidden Features of ASP.NET
Hidden Features of JavaScript
Hidden Features of PHP?
Hidden features of Ruby
Hidden Features of C++?
Hidden Features of Visual Studio (2005-2008)?
Hidden features of Python
Hidden Features of VB.NET?
Hidden Features of Delphi
Hidden features of Greasemonkey
Hidden Features of SQL Server
Hidden features of D
Hidden features of C
Hidden features of Perl?
Hidden features of windows command line
Hidden features of MSDN documentation
Hidden features of Stackoverflow

question feed
about faq blog podcast privacy policy advertising info contact us feedback always welcome
stackoverflow.comserverfault.comsuperuser.commeta howtogeek.com doctype.com

svn revision: 4497
site design and logo is © 2009 stackoverflow.com llc; user contributed content licensed under cc-wiki with attribution required
document.write(unescape("%3Cscript src='http://www.google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

var pageTracker = _gat._getTracker("UA-5620270-1");

_qoptions = { qacct : "p-c1rF4kxgLUzNc" };

Friday, September 11, 2009

How to become a faster programmer

Someone asked this on http://stackoverflow.com/questions/1411394/how-to-become-a-faster-programmer

In reading his post, I realized that he had confused timeliness with speed. The two are not the same:

My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.
Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?
How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?
Any feedback is greatly appreciated, thanks,

My response:

I think they key word here is "timeliness". They didn't say you were too slow, rather that you were not timely.

In project management, it is important for the manager to be able to estimate when your work items will be complete with accuracy. I suspect that the main reason why your efforts were not deemed to be timely is that you frequently had items that were not delivered on schedule, and were delivered much later than scheduled.

To improve your timeliness, you might want to spend more time understanding how long it will take you to complete a particular work item given your skills, experience, and the domain. This will allow you to give better estimates to your project manager. The key here is "better" ... you could deliver on time more frequently by padding everything with a fudge factor, but what you really want to strive for is a more accurate estimate.

I would discuss this with your manager to see if this is actually the issue. Otherwise, you might end up programming twice as fast, promising things in half the time you used to, and still getting criticized for your timeliness because your estimates will still have the same error factor.

use of goto versus runtime code evaluation

Asked on stackoverflow.com: http://stackoverflow.com/questions/1412620/use-of-goto-versus-runtime-code-evaluation

Recently for a programming class, we were given the assignment to write a program in any language that, given n, will produce all the possible derangements for an array p of size n such that p[i] != i for all i: 0 <= i < n. We had to use iterators, e.g. yield.
Example: n=3, [0, 1, 2] is not a derangement, but [2, 0, 1] is as well as [1, 2, 0].
I came up with a pseudocode solution that would work, but the problem was that it required power loops (that is, n nested loops where n is only known at runtime). To do this, I generated n nested loops in Ruby code in a string, then eval-ed the string. My solution worked, however my professor thought that using a few gotos would have been better solution (easier to read, at least) than dynamic code generation.
I was under the impression that goto was always a bad choice. Why might runtime evaluation of dynamically generated code be a worse choice than goto? The generated code is clean and simple, and seems fairly efficient for the given problem. The only user input upon which the code generation depends is n, which is checked to ensure it's an integer value beforehand. It yields only unique derangements, as it should.
I'm not asking for a solution to my programming assignment, I just want to know reasons behind the use of goto over dynamic code evaluation, or vice versa.
Edit: to clarify, the assignment included writing a program using iterators and another using recursion, so the iterative version wasn't necessarily meant to be efficient.

My responses:

Here's a solution with early pruning. Mhy only question is regarding enumerations: did he want you to create an enumerator that on each successful call would generate the next item in the list? This would probably be easiest implemented by creating a lambda version of this program - I used to do this in lisp all the time when writing query generators that would generate the next answer to a question when doing prolog-interpreter style queries.


Non-recursive version using goto:

Option Strict On
Option Explicit On
Module Module1
Dim x As Stack
Private Sub printGeneratedList(ByVal generatedList As List(Of Integer))
For Each el In generatedList
Console.Write(el & " ")
End Sub
Private Sub generateAux(ByVal i As Integer, ByVal n As Integer, _
ByVal generatedList As List(Of Integer))
Dim stackI As Stack(Of Integer) = New Stack(Of Integer)
Dim stackJ As Stack(Of Integer) = New Stack(Of Integer)
Dim j As Integer
j = 0
If i >= n Then
If stackI.Count = 0 Then
GoTo ReturnLabel
End If
End If
While j < n
If Not j = i Then
If Not generatedList.Contains(j) Then
i = i + 1
GoTo StartLabel
i = stackI.Pop()
j = stackJ.Pop()
End If
End If
j = j + 1
End While
If stackI.Count = 0 Then
GoTo ReturnLabel
End If
End Sub
Private Sub generate(ByVal n As Integer)
Console.WriteLine("Generating for n = " & n.ToString())
Dim l As List(Of Integer) = New List(Of Integer)
If n < 0 Then
Throw New Exception("n must be >= 0")
End If
generateAux(0, n, l)
End Sub
Sub Main()
End Sub
End Module


Recursive version:
Private Sub generateAux(ByVal i As Integer, ByVal n As Integer, _
ByVal generatedList As List(Of Integer))
If i >= n Then
End If
For j As Integer = 0 To n - 1
If Not j = i Then
If Not generatedList.Contains(j) Then
generateAux(i + 1, n, generatedList)
End If
End If
End Sub

Why Clojure over other JVM Lisps: Kawa, Armed Bear or SISC?

Asked on stackoverflow .. here are some of my responses

The advantage of Clojure is that it gives you access to all the java libraries/code out there, and multi-threading support because it's based on the JVM. In addition it was designed with concurrency in mind, something not generally designed into lisp, although because of the mapping primitives it probably wouldn't be hard to design a lisp that would support concurrency well.
That being said, I tried Clojure and hated the syntax and the pain in the butt factor that seems to go along with anything Java-connected.


I should also add that Clojure is a relatively new language, implemented by one person, with good marketing skills and a lot of energy. He's investing a lot of time and hype into clojure ... sometimes, the hype is a self-fulfilling prophecy in that if you can convince enough people that it's the latest greatest thing, then you can get enough support and momentum to make it actually work.

I suspect the implementers of Kawa etc. don't have as much at stake, hence are not hyping their product. Besides, what's there to hype? "We've got a great language .. it's called Lisp" It's a harder marketing sell.

I think Java is a prime example of this. It had some very serious deficiencies, but because it was marketed and hyped so heavily it achieved a lot of momentum which meant support from hardware/software vendors, producers of tools, investment by industry, etc. Either way, it achieved a certain degree of success, although I hated programming in it. Clojure might achieve a similar success where other Lisps have not.


yes, but the question was in comparison to other Lisps on the JVM, which also have access to Java libraries. – Rainer Joswig 1 hour ago


They have access to Java libraries through a foreign function interface -- but with Clojure, since the code/data is compiled down to the JVM, the java code can also operate on the Clojure data structures. This gives a tighter and more seamless integration with Java. But, for me this is like having a closer and more intimate relationship with a girl that you don't really like or find attractive :) You can do it but what's the point? – Larry Watanabe 13 mins ago

Automatinv Visual Studio Build 2008

Answers from stackoverflow.com:

With VS2008 you can do this:devenv solution.sln /build configuration
answered Aug 29 '08 at 6:38

Agnel Kurian3,129●10●24

This way always seems the easiest. – Aardvark Sep 25 '08 at 22:53
add comment
\Windows\Microsoft.NET\Framework\[YOUR .NET VERSION]\msbuild.exe
Lots of command line parameters, but the simplest is just:msbuild.exe yoursln.sln
answered Aug 23 '08 at 20:46

add comment
nant and msbuild are the most popular tools to automate your build in .net, and you can can find a discussion on there the pros/cons of each in this question "best .net build tool"
edited Aug 23 '08 at 21:02
answered Aug 23 '08 at 20:52

add comment
Look into build tool NAnt (http://nant.sourceforge.net/) or MSBuild (http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx). I believe MSBuild is the build tool for VS2005+, I am however a fan of NAnt...
answered Aug 23 '08 at 20:43

add comment
As of VS2005, all of the project files (at least for .NET based projects) are actual MSBuild files, so you can call MSBuild on the command line and pass it the project file.
Bottom line is that you need to use a "build scripting language" like NAnt or MSBuild (there are others, but these are the mainstream ones right now) if you want to have any real control over your build process.
answered Aug 28 '08 at 17:09

Scott Dorman9,212●9●29
add comment
Simplest way: navigate to the directory containing the solution or project file, and run msbuild (assuming you have Visual Studio 2005 or newer).
More flexible ways:
read up on the MSBuild reference. There's tons of customization, especially once you've installed the community tasks.
use NAnt. It has existed for longer than MSBuild and has more community support, but requires you to start a project file from scratch, rather than extending the existing, VS-created one.
answered Aug 23 '08 at 20:44

Sören Kuklau4,660●6●18
add comment

I had to do this for a C++ project in Visual Studio 2003 so I don't know how relevant this is to later version of visual studio:
In the directory where your executable is created there will be a BuildLog.htm file. Open that file in your browser and then for each section such as:Creating temporary file "c:\some\path\RSP00003C.rsp" with contents[/D "WIN32" /D "_WINDOWS" /D "STRICT" /D "NDEBUG" ..... (lots of other switches).\Project.cpp.\Another.cpp.\AndAnother.cpp".\And Yet Another.cpp"]Creating command line "cl.exe @c:\some\path\RSP00003C.rsp /nologo"
create a .rsp file with the content between the square brackets (but not including the square brackets) and call it whatever you like. I seem to remember having problems with absolute paths so you may have to make sure all the paths are relative.
Then in your build script add the command line from the BuildLog.htm file but with your .rsp filename:cl.exe @autobuild01.rsp /nologo