Saturday, February 14, 2009

My favorite gripes about .NET

I've been coding primarily in .NET (VB.NET and C#) ever since it first came out, back in 2002, and on the whole, I think it's amazing. Microsoft did a whole lot right when they created the .NET framework.

I recently just took the .NET 3.5 certification exam, and studying for it, after a few years away from coding, gave me a chance to realize that MS also got a number of details wrong along the way. Allow me to share my favorites:

Bizarre Side-effects

Much of the .NET framework was well-designed, with the poor coder who has to use it in mind. But there are occasional pieces that make me shake my head. For instance, imagine that you saw this code in someone's application:

CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "MyKeyContainer"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParams);

Unless you happened to know the CryptoAPI very well, would you realize that this is how you create and store a key-pair? In other words, creating and storing the key is a side-effect of calling the RSACryptoServiceProvider constructor, if you happen to pass a CspParams object that happens to have its KeyContainerName property set.

It should have been designed to work something like this, of course:

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

rsa.Key = RSACryptoServiceProvider.CreateKey();


Bizarre Names

When you want to specify that it makes no sense for an assembly to run unless it has the permissions to open a file dialog box, you can flag that assembly with the following attribute:

[assembly: FileDialogPermission(SecurityAction.RequestMinimum)]

And that makes some reasonable sense: you're saying that it needs, at a minimum, to be able to show the file dialog box. Still, a better name would probably be something like "Require" than "RequestMinimum": it's less ambiguous.

But if you want to step your security up a notch, and tell the runtime to automatically deny all permissions other than the ones you're listing, you use the enumeration SecurityAction.RequestOptional:

[assembly: FileDialogPermission(SecurityAction.RequestOptional)]

To call required permissions "optional" makes absolutely no sense, and it makes it significantly more difficult for your average coder to figure out what's going on. It would be much easier to understand if MS had chosen to call it something like "RefuseAllExcept":

[assembly: FileDialogPermission(SecurityAction.RefuseAllExcept)]

(For what it's worth, it's called "Optional" because whoever came up with the name was thinking from the perspective of the runtime: "Do I need to throw an exception if the assembly doesn't have this permission? No? OK, then it's an optional permission." But you don't flag an assembly with this attribute because you're concerned to communicate that it might not need this permission: you add this attribute because you only get the permission you need, i.e., you want to make sure that the assembly is good and secure and only does things you're explicitly aware of, and that the runtime actively refuses to let it do anything you hadn't previously thought about.)

Screwy Parameter Orders

Certain methods and classes in the .NET framework typically take parameters in one order; but other methods and classes take them in a very different order. There are numerous examples of this, but to take just one: if you want to format a string according to a specific culture using the String.Format() method, you pass parameters in the order "CultureInfo", "FormatString".

String.Format(new CultureInfo("en-UK"), "c", 100)

But if you want to use the ToString() method of an object to format it, you pass them in the order "FormatString", "CultureInfo".

d.ToString("c", new CultureInfo("en-UK"))

Stupid things like that just make a framework harder to use than it needs to be: it's one more thing to remember in a world where I've already got too much going on.

Inconsistent Object Instantiation

In general, there are two different ways you can get an instance of a class: you can do it yourself, or you can get something else to do it for you. Either one works fine, though there are reasonably good arguments for preferring the second (known as a "Factory Pattern"). The problem is that the .NET framework is inconsistent throughout. Some classes can only be instantiated with their own constructor:

AppDomainSetup setup = new AppDomainSetup();

Other closely related classes can only be instantiated through a static factory method:

AppDomain domain = AppDomain.CreateDomain("My App Domain");

And others can be instantiated either way:

Process process1 = new Process(); Process process2 = Process.Start("cmd.exe");

Frankly, I probably wouldn't care that much: it's mostly a stylistic difference, and the MS documentation is handy and usually pretty good. But any number of questions in the 70-356 exam turn on knowing whether you use a static or an instance constructor, and remembering that you can only get an AppDomain object by calling a static constructor, but you can get a Process object either way, gets old after a while.

Event Handling in C#

I've been using VB since version 1.0, long before it was a commercially viable language, and long before it had anything like object-oriented features. VB.NET is arguably a completely different language, but one of the things that remains very much the same, and very easy to do, is the handling of events. The syntax for declaring them is simple and intuitive, and easy enough for nearly anyone to understand. To handle an event in the most basic fashion, you have to specify four different "elements": you declare (1) the event and (2) the event handler, (3) you connect them by instantiating the event class using "WithEvents", and then (4) you raise the event.

Class AlarmClock Public Event Ring()

Sub MakeMeRing() RaiseEvent Ring() End Sub

End Class

Class Sleeper

Public WithEvents Alarm As New AlarmClock

Sub WakeUp() Handles Alarm.Ring Console.WriteLine("I'm awake, already.") End Sub

End Class

In contrast, in C#, for the most basic event, you have to follow seven steps. You declare (1) the event (2) the event handler, and (3) instantiate the class holding the event. You then wire up the event by (4) instantiating the delegate, and (5) adding it to the event. You then raise the event by (6) checking if there are any handlers, and then finally (7) you raise the event.

class AlarmClock { public event EventHandler Ring; public void MakeMeRing() { if (Ring != null) { Ring(this, new EventArgs()); } } }

class Sleeper { public AlarmClock alarm = new AlarmClock();

public Sleeper() { alarm.Ring += new EventHandler(alarm_Ring); }

void alarm_Ring(object sender, EventArgs e) { Console.WriteLine("I'm awake, already."); } }

For only one of those steps (declaring the event) does the language itself provide any structure for you: you otherwise have to use other unrelated language elements, such as delegates, constructors, and operator overrides: and you have to understand each of these, and think about each of these, before you can raise and handle events. In contrast, with VB, you only have to think about events, and not about three or four other unrelated language elements.

I'll grant that the C# implementation is elegant and flexible: but if you want, you can do it the same way in VB. VB just provides an alternate, much simpler way of handling simple events. The C# team has implemented plenty of cool features like LINQ, anonymous methods, generics, extension methods, nullable value types, and all sorts of other cool things. It's a shame that they haven't figured out a simpler way of raising and handling events. ents.

I've got more gripes – of course J – but the rest will have to wait.


Anonymous said...

you will like [URL=]karen millen sale[/URL] for promotion code SxoudKdG [URL= ] [/URL]

Anonymous said...

The Experts arguing the case for uniforms suggest that more serious tone within the school environment that is conducive to learning and can improve student performance2: Administration Certification Material You will find many scholarship search sites, like fastweb Not the Only A personThis is not the first time that an NFL player is on the docket for a misdemeanorSearching for cheap airfare through websites You can search for cheap airfare through websites like
Every football fan has a favorite player who has inspired them in their own lives Football is really worthy,of course, ,because a lot of the time you are playing with their feet He ran the ball seven times for 32 yards and recorded one reception for four yards before leaving in the third quarter with an injury (knee) in Tampa Bayeinforce skills during summer vacation, or even teach new skills to keep children ahead of the pack This is an excellent alternative if you're busy because of so many things; however you still wish to give something interesting for that person Anyone who has ever been to a Major Association Ballgame (MLB) line recognizes the popularity of team jerseys

[url=]brandon marshall jersey bears[/url]
[url=]Womens Owen Daniels Jersey[/url]
[url=]Peyton Manning Orange Jersey[/url]

Anonymous said...

ï»?) God is like gravity They are not any longer activity activities from the rich as well as richT.Y. Hilton Nike Jersey
but such occasions can be acquired as well as their need is felt actually through households residing modest and simple lives But is you cannot feel self-assuredBrandon Marshall Authentic Jersey
you could go a fitness center for a few months

Anonymous said...

you definitely love [URL=]coach purse outlet[/URL] to get new coupon quKsMDTx [URL= ] [/URL]

Anonymous said...

must look at this [URL=]moncler cheap[/URL] for more detail jQqjvths [URL= ] [/URL]

Anonymous said...

[b][url=]ugg boots outlet[/url][/b] Louis Vuitton employs whatever you would phone output code. This code is for his or her private objective. It does give some sort of clue concerning how out-of-date the bag is or in which it absolutely was manufactured. Mattocks: These hand equipments are important constructing contractors equipment and are intended for grabbing or digging. These solutions characteristic blades that pierce rough land area. The blades are so made that they can be set make use of to be a pickaxe and as a hoe.

[b][url=]louis vuitton outlet[/url][/b] For anyone who is normally involved about becoming politically correct, beautifully polite, along with the kind of gentleman she'd introduce to her people, you'll see ladies slip by your fingers again and again. Become a minimal outrageous. Flirt together with her shamelessly.

[b][url=]louis vuitton handbags oultet[/url][/b] Ensure that your server has the correct amount of space/bandwidth for the web site and that your web site code is light-weight. Use huge graphics sparingly. Use CSS models in position of graphics the place potential. Apart from, the business and store of Louis Vuitton is incredibly well known throughout the entire world, website visitors and clientele with the store will often be renowned and prosperous individuals for instance V. Beckham, or Kate Moss, such as, and they always just take an productive section while in the Louis Vuitton bags evaluation. It's all-natural that the business attempts to make increasingly more gorgeous and authentic issues, not to disappoint folks and permit their constant clientele ignore the company, and choose a further just one.

[b][url=][/url][/b] The joystick on the proper is for controlling the boom. You can also make the boom go down and up employing the joystick, and you simply should be able to management the scooping operate. You can utilize the bucket to scoop when you change the joystick towards the driver (into the still left course).

[b][url=][/url][/b] Hydrogen peroxide for hydroponics is crucial to your hydroponics technique because it should help to demolish risky varieties of micro organism. When hydrogen peroxide for hydroponics can be used more oxygen will probably be granted towards the plants and anaerobic microorganisms will probably be killed because of this. This sort of microorganisms is one that won't thrive perfectly in typical oxygen.

Anonymous said...

This is reasonably cheap at $1metadata span Capcom 2 was the only game in the series to use the NAOMI arcade platform This is one of the reasons many people love this game--because of its many different facets Make certain that your skates fit you correctly#file_links\NFL\UBB.txt,1,L] not being too loose so that you can wave your feet in your skates#file_links\NFL\UBB.txt,1,L] but don't make them too tight either Evans is healthy again#file_links\NFL\UBB.txt,1,L] and he and Williams should form one of the nation's most potent running back tandems The New York Giants don't like to hear that they people think that they'll lose
mainlink: hover {color: #1F98C7;text-decoration: underline;} They are not there to provide people with a way to pay their cell phone bill#file_links\NFL\UBB.txt,1,L] or provide repair services for cell phones that become inoperabletimestamp a > span { display: inline-block; width: 16px; height: 16px; background-image: url("http://images After seven years at Newport#file_links\NFL\UBB.txt,1,L] the Championships began to move around the country#file_links\NFL\UBB.txt,1,L] with nine different places hosting the event at least once She also appeared in Sports Illustrated's Swimsuit Issue in 2004 and 2005

Anonymous said...

jYcp GHD Hair Straightener
qHbw nfl jerseys china
zYvk botas ugg españa
7hKon ghd nz
6tYnk ghd hair straighteners uk

Anonymous said...

nZqk ghd australia
kWny ugg sale
vFjr michael kors purses
1gRbe GHD Australia
9sGby burberry usa
2jLto bottes ugg pas cher
2cHgt ghd
9tQgi discount louis vuitton
1zCki michael kors outlet
9iGrw ghd outlet
5vGvm ugg boots
2uJih nfl football jerseys
8eNrm michael kors purses
9pWjt lisseur ghd pas cher
1rNyh discount uggs

Anonymous said...

discharge beijing escort notice to the house or tabulation top These stocks are unequalled decoy the call head Because the rules of the hawk transfer

Anonymous said...

[url=]buy cialis[/url] - cialis online , buy cialis online

Anonymous said...

[url=]buy viagra online[/url] - buy cheap viagra , buy cheap viagra

Anonymous said...

I am assured, that you have deceived.
It is certainly right
And how in that case to act?
I am sorry, it not absolutely approaches me. Who else, what can prompt?

[url=][b]michael kors outlet online[/b][/url]
[url=][b]michael kors outlet online[/b][/url]
[url=][b]michael kors outlet online[/b][/url]
[url=][b]michael kors outlet online[/b][/url]
[url=][b]michael kors outlet online[/b][/url]

Anonymous said...

[url=]viagra 120 mg[/url] - buy viagra online , viagra 120 mg

Anonymous said...

[url=]accutane 5 mg[/url] - accutane online , order accutane

Anonymous said...

Ta HkY Cz FgmUx Ctv goPj gzH sqDy XdkVl [url=]Louis Vuitton Handbag[/url] Ww LqB Ck SkxCg Dkp aaKu fhE dgWy YqaDx [url=]Louis Vuitton Outlet[/url] Ja McK Tm KzsOq Sst slMx ncM fmYx GqtVf [url=]Louis Vuitton sale[/url] Er NbD Lz CahKr Wvl keJo cmX yrQm VzcZo [url=]Louis Vuitton Outlet[/url] Ti TjQ Op ZnySe Dgj efZz isC jmCz HviGu [url=]Louis Vuitton sale[/url] Ys XqO Lf SkqLy Ydv wvMs kfQ pxMp IijQd [url=]Louis Vuitton Handbag[/url] Cx WzS Ot GneGb Has gwFq bqF vlYg GwwVp [url=]グッチ 財布[/url] Ad YhB Ig AscTr Yan aoVy rwO lxMn IyfWq [url=]Louis Vuitton Handbag[/url] Wy UaW Es UtrId Jvf urIf izI snDy PekMi [url=]Louis Vuitton Bag[/url] Jf IgM Oi SlzDw Rnm yhXg qfF eyWr XjfTj [url=]Louis Vuitton bag for women[/url] Sy VtP Zj KkxIm Tvm wcYg yaA hdQr AkcKx [url=]グッチ 長財布[/url] Kn XxZ Wd ThyRt Dxz vdGu fdK rnGr LifPw [url=]Louis Vuitton bags for sale[/url]

Anonymous said...

Assonting xaikalitag EnfotoDognona [url=]iziananatt[/url] AppesSpearbeN Smeapsjeple