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


Questions
Tags
Users
Badges
Unanswered
Ask Question
Hidden Features of C#
762
1,112
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:
Keywords
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
Attributes
DefaultValue by Michael StumObsoleteAttribute by DannySmurfDebuggerDisplayAttribute by StuDebuggerBrowsable and DebuggerStepThrough by bdukesThreadStaticAttribute by marxidadFlagsAttribute by Martin ClarkeConditionalAttribute by AndrewBurns
Syntax
?? 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
Framework
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
Other
netmodules by kokosLINQBridge by Duncan SmartParallel Extensions by Joel Coehoorn

editflag
edited Sep 9 at 11:35

roosteronacid
community wiki
34 revisions, 17 usersSerhat Özgel 16%
1


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


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
209
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;
linkeditflag
answered Aug 13 '08 at 1:53

ageektrapped
community wiki

14


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


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
6


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
17


@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
10


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
176
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;
linkeditflag
edited Aug 27 '08 at 1:34

John
community wiki
2 revisions
1


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


Nice! Definitely cleaner than 3 if statements! – SkippyFire Jun 5 at 18:12
add / show 1 more comment
166
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 :-)
linkeditflag
edited Apr 6 at 12:45

edg
community wiki
4 revisions, 2 users
add / show 6 more comments
156
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.
linkeditflag
answered Aug 15 '08 at 11:06

John
community wiki

33


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
9


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
9


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
6


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
4


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
153
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).
linkeditflag
edited May 8 at 17:26

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


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
3


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
15


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
15


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
11


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
131
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.
linkeditflag
answered Aug 12 '08 at 16:42

Mike Stone
community wiki

3


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
2


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
1


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
5


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
127
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();
linkeditflag
edited Aug 29 '08 at 16:22

Keith
community wiki
5 revisions
2


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
1


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


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
122
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()); } }
linkeditflag
edited Aug 18 at 18:18

Will
community wiki
4 revisions
4


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
4


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


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
101
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
linkeditflag
answered Sep 16 '08 at 16:53

BlackTigerX
community wiki

3


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
3


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


Holy .... this one truly made reading this post worthy. 8) – Arnis L. Jun 6 at 19:41
add / show 1 more comment
98
"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
linkeditflag
edited Aug 12 '08 at 16:53

Michael Stum
community wiki
3 revisions
8


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
94
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()}
linkeditflag
answered Aug 13 '08 at 7:39

lomaxx
community wiki

2


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


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
11


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
85
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
linkeditflag
edited May 8 at 21:18

Lucas
community wiki
3 revisions, 3 userslomaxx 75%
3


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
79
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.
http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx
linkeditflag
edited Aug 20 '08 at 14:50

Keith
community wiki
2 revisions, 2 users
add / show 8 more comments
73
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.
linkeditflag
edited Aug 12 '08 at 19:01

Patrick
community wiki
2 revisions
11


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
65
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.
linkeditflag
answered Sep 9 '08 at 21:52

jolson
community wiki

add / show 1 more comment
64
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.
linkeditflag
answered Aug 13 '08 at 10:20

deathofrats
community wiki

1


Cool! I have to remember this! – Dave Van den Eynde May 28 at 14:56
add comment
63
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;
linkeditflag
answered Sep 23 '08 at 20:39

richdiet
community wiki

2


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


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

boj
community wiki
2 revisions, 2 usersboj 56%
1


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

Mark Cidade
community wiki

11


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
2


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
10


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
2


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
5


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

Barry Kelly
community wiki
2 revisions, 2 users
22


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
2


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


Store values of a ThreeState CheckBox – Shimmy Jul 13 at 15:04
add / show 9 more comments
50
@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.
linkeditflag
answered Aug 12 '08 at 18:03

Dogmang
community wiki

4


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
50
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;}
linkeditflag
answered Aug 17 '08 at 1:01

dp
community wiki

2


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


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
1


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


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
45
If you want to exit your program without calling any finally blocks or finalizers useEnvironment.FailFast()
linkeditflag
answered Oct 13 '08 at 22:25

Jan Bannister
community wiki

1


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


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

nt
community wiki

1


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


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
41
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.
linkeditflag
edited Mar 4 at 18:19

Joan Venge
community wiki
2 revisions, 2 usersJudah Himango 76%
add / show 1 more comment
39
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.
linkeditflag
answered Aug 16 '08 at 23:55

Brad Wilson
community wiki

add / show 2 more comments
38
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;
linkeditflag
answered Aug 19 '08 at 15:54

JasonS
community wiki

1


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
4


@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
4


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
37
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"
linkeditflag
answered Aug 18 '08 at 22:29

Portman
community wiki

add comment
35
?? - 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
linkeditflag
edited Aug 12 '08 at 16:39

kokos
community wiki
2 revisions
5


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


@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
33
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...
linkeditflag
edited Aug 17 at 12:41

Dave Markle
community wiki
3 revisions, 3 usersKiwiBastard 67%
1


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


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.
tagged
× 38168 × 89
asked
1 year ago
viewed
66,448 times
latest activity
today
document.write('');
document.write('');



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


Wanted: Lead Software Engineer - Web Mining at Untangly, inc. (Mountain View, CA). See this and other great job listings at jobs.stackoverflow.com.
Related
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");
pageTracker._trackPageview();

_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:


1
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

----
2
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 & " ")
Next
Console.WriteLine()
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
StartLabel:
j = 0
If i >= n Then
printGeneratedList(generatedList)
If stackI.Count = 0 Then
Return
Else
GoTo ReturnLabel
End If
Return
End If
While j < n
If Not j = i Then
If Not generatedList.Contains(j) Then
generatedList.Add(j)
stackI.Push(i)
stackJ.Push(j)
i = i + 1
GoTo StartLabel
ReturnLabel:
i = stackI.Pop()
j = stackJ.Pop()
generatedList.Remove(j)
End If
End If
j = j + 1
End While
If stackI.Count = 0 Then
Return
Else
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()
generate(0)
Console.ReadLine()
generate(1)
Console.ReadLine()
generate(2)
Console.ReadLine()
generate(3)
Console.ReadLine()
generate(4)
Console.ReadLine()
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
printGeneratedList(generatedList)
Return
End If
For j As Integer = 0 To n - 1
If Not j = i Then
If Not generatedList.Contains(j) Then
generatedList.Add(j)
generateAux(i + 1, n, generatedList)
generatedList.Remove(j)
End If
End If
Next
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:


5
With VS2008 you can do this:devenv solution.sln /build configuration
linkflag
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
9
\Windows\Microsoft.NET\Framework\[YOUR .NET VERSION]\msbuild.exe
Lots of command line parameters, but the simplest is just:msbuild.exe yoursln.sln
linkflag
answered Aug 23 '08 at 20:46

FlySwat21.5k●3●31●98
add comment
2
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"
linkflag
edited Aug 23 '08 at 21:02
answered Aug 23 '08 at 20:52

alanl323●2●7
add comment
2
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...
linkflag
answered Aug 23 '08 at 20:43

mmattax5,274●2●11●46
add comment
1
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.
linkflag
answered Aug 28 '08 at 17:09

Scott Dorman9,212●9●29
add comment
1
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.
linkflag
answered Aug 23 '08 at 20:44

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

0
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