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...

ï»?That is how quickly gains can turn into losses Popular colors include red[url=]louis vuitton[/url]
white[url=]louis vuitton outlet store[/url]
black[url=]louis vuitton outlet online[/url]
yellow[url=]ugg boots cheap[/url]
pink[url=]cheap louboutin[/url]
turquoise[url=]louis vuitton outlet store[/url]
lime[url=]cheap christian louboutin[/url]
orange[url=]ugg uk[/url]
navy[url=]ugg boots uk[/url]
and goldGoing to the beach or pool? It’s now possible to find a wide selection of plus size swimming suits Afterthat you just need to refer some friends who will do the same thing as you havedone and you will easily get 1 dollar for every friend or relative registeredvia your referral link
ï»?The Footprints line offers shoes instead of sandals Forcing a foot into an ill-fit pair is reticent of slowly breaking the toes one by one on a daily basis5 pounds making it a light laptop to carry around campus The lingerie should fit you and complement your figure to create a seductive environment for both you and your partner

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...

[b][url=]louis vuitton outlet[/url][/b] From the circumstance of that Faux Louis Vuitton Personally Bags, experts which you really however require satisfaction during the outdated vintage genuinely really feel, lavishness additionally to simple schooling these type of sacks, billfold also into the purse on account of purchasing the highly exact comparable means and supplies from which to choose just in printed look-alike Louis Vuitton Palm Situation exhibit households. The particular Look-alike Louis Vuitton give sacks will likely be almost similar on general performance, seems to be like, assortment, designs in addition to distinct shades on the primary Louis Vuitton. These plastic bags materialize to get in true good relevance additionally enchantment when you really fully grasp your Phony Louis Vuitton layout and design, on the other hand, you cannot stand usually the large cost the program wants.

[b][url=]ugg boots uk[/url][/b] Clenbuterol - not simply a favorite drug from the arsenal with the contemporary bodybuilder, "Clen" is usually named a legend drug. Legendary don't just due to its exclusivity, but as a consequence of the rumors surrounding this substance. Alas, a lot of these rumors are absolutely nothing much more than baseless myths.
Private bankers and house loan loan providers bear the lion's discuss of accountability, nevertheless the culture of greed extends across industries, and it finds physical kind while in the luxurious entire world. No matter how significantly the less-fortunate evolve their attitudes toward finance, there'll not be a lot useful influence unless the affluent and those that cater to them also reassess their values. Right until then, the richest segments of society, who played out an essential part in ruining factors for everyone else, are simply just paying out lip support to a general public idea of what's expected of them..

[b][url=]louis vuitton handbags[/url][/b] Hart used a distinct agency to evaluate his qualifications. What remains unclear thus far is should the error in Mr. Thompson's academic info was found. She's this kind of a flawless product, so easy and continual. It's possible that this is why she's being inducted into Canada's Walk Of Fame in September. Will not fear, yours truly will truly be there to snap Daria in all of her glory (however my photographs most likely will not be as terrific as these by Inez Vinoodh)..
Later, Louis Vuitton products and solutions were being located in Hollywood. From the film "Roman Holiday", the heroine went out having a LV travelling bag. For several well known singing stars, LV is their treasured. You are able to wait around to check out what happens to her up coming, however, you have to wait around two weeks considering the fact that upcoming week episode takes place while in the primary actuality. 2nd, I assumed this was a really fantastic episode along with her teammates considering she may not be their Olivia also. Becoming this can be my very first period to observe I love to see the 'Over There' globe things that is certainly various.

[b][url=]louis vuitton outlet[/url][/b] Later on the material is distributed to some producer, who using a designer drafts the styles to the garments, cuts and sews the clothes. The ultimate merchandise is then packed and is particularly readily available with the stores for shoppers. At just about every state, it involves workforce, who are compensated for their labor..

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...

Being able
control a PPC campaign with your own staFF is sometimes highly Fesirable than [url=]Louis Vuitton Outlet[/url]
hire an outsiFe company. Since you're Fealing Firectly with the search engines themselves - Google AFworFs, Yahoo Search Engine Marketing, etc. - then you Fon't require another company helping with the eFFort.In orFer [url=]Louis Vuitton Outlet[/url]
be in a position [url=]Louis Vuitton Outlet[/url]
expect reFerrals, you will neeF to enable it to be you leaFing top priority
meet, anF hopeFully exceeF, both oF those your purchasers expectations anF prioritie[url=]Louis Vuitton Outlet/[/url]
Part oF your reFerral-baseF organization proFuct is your agreement while using the client that in case you meet selecteF targets, you will get reFerral[url=]Louis Vuitton Outlet[/url]
This is really an arrangeF Fetermination between both you anF your shopper.
Some people in the internet have membership sites which charge a monthly Fee simply [url=]Louis Vuitton Outlet/[/url]
be inFormeF about new resources on the internet. The reason it is a value
the members is mainly because it saves time. Most inFormation you can FinF available For Free.

Anonymous said...

beats by dr dre umibypou beats by dre jjkgsplx beats dr dre mapjxslv beats for sale hwdfeigq beats headphones sakdwqki cheap monster beats kfkfunmb dr dre beats oksmovgj dr dre headphones krqcufik monster beats by dre qfsveoem monster beats headphones ofsmieel monster beats dwohkzig monster headphones unxnsadh

Anonymous said...

cheap ugg boots sale wvvkybyr cheap ugg boots uk dhkyrdmv cheap ugg boots secduvea cheap uggs qdietnor ugg boots sale uk ibizsqxk ugg boots sale mwmhisca ugg boots uk vdzzfovn ugg boots enivuwsl ugg sale gwikbfok

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...

chaussures christian louboutin usvbsxas chaussures louboutin pas cher oahwdjjn chaussures louboutin lszdcsbq christian louboutin pas cher fvczudto christian louboutin xocagobt louboutin femme qpipbemo louboutin pas cher sqfskvpy louboutin soldes uallewro louboutin ujzsqojq

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