Which kind of cast should you use in C#?(gen5.info)

submitted by paul_houlepaul_houle(435) 3 years, 11 months ago

C# offers two casting operators: the prefix-cast and the as-cast. Although the two operators compile to different op-codes in the CLR, the practical difference between them is in how they handle failed casts. Prefix-cast throws an exception on cast failure, while as-cast returns null. It’s easier to implement correct error handling when you use prefix cast, because it doesn’t require manual checks for null values that can cause problems in distant parts of your program. Prefix-cast should be the default cast operator on your fingertips, that you use for everyday situations — reserve as-cast for special cases where performance matters.

3 comments |category: |Views: 493

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by confuzatronconfuzatron(0) 3 years, 11 months ago 0

The cutting-edge inside dope on advanced C#.

Reply

posted by JudahGabrielJudahGabriel(814) 3 years, 11 months ago 0

The article focuses on performance aspects. This is bad because performance of casting is a micro-optimization on the greatest scale.

The two primary concerns should be behavior and readability:

Behavior: casting will throw if the type is not convertible, the 'as' operator will simply return null if the type isn't convertible.

Readability: the 'as' operator reads cleaner than a cast in parens.

Reply

posted by aquinasaquinas(20) 3 years, 11 months ago 0

I don't think "as" is faster.

Reply

information Login or create an account to comment on this story