C #4.0 programming tips and tricks

Source: Internet
Author: User
Introduction

Welcome to this installment of the. NET Nuts & bolts column! When it comes to tips and tricks there are using items that can be considered. for this article we'll briefly recap the C #4.0 language features, cover some tips, tricks, and reminders, and touch on a couple of useful tools.

C #4.0 Overview

C #4.0 contains four primary areas of emphasis.

    • Dynamically typed objects
    • Optional and named Parameters
    • Improved com interoperability
    • Co-And contra-variance

The last. net nuts and bolts article covered named and optional parameters and covered how it is responsible for some of the improved com interoperability when interacting with DLLs such as the office integration components. while named and optional parameters are available inC # ProgrammingNow, it is important to establish ground rules for responsible use. The following table outlines considerations for when to use each.

<Table align = "center" border = "0" cellspacing = "0" cellpadding = "0" width = "100%"> <tr> <TD valign = "TOP"> <p> <B> when to consider overloading: </B> </P> <ul> <li> when defaults are not compile-time constants </LI> <li> when alternatives specify different types </LI> </ ul> </TD> <TD valign = "TOP"> <p> <B> when to consider optional parameters: </B> </P> <ul> <li> when you only need to specify default values for the optionals, especially if there are a number of optionals </LI> </ul> </TD> </tr> </table>

 

Extension methods

Extension methods allow you to add new functionality on existing types. this ability even includes des the ability to add new functionality to sealed classes. they are declared like static methods and called like instance methods. they are scoped by using clses and are valid for interfaces and constructed types. the following code example demonstrates adding two methods to the decimal type from. NET Framework.

 

 
Static class extensionsample {public static decimal triple (this decimal d) {return D * 3;} public static decimal half (this decimal d) {return D/2 ;}} decimal y = 14 m; y = y. triple (). half ();

 

When building extension methods within your code base it is recommended to consider a separate namespace to allow them to be optional. it is also best you not be mean to others by applying to all objects by extending object. the following sample demonstratesWhat not to doAs it alters the default behavior of all classes. Normally accessing a property or method on an object that is nullNullreferenceexceptionWocould be generated. The extension method below wocould Add. Isnull ()Method that wocould alter that behavior, which then makes your code behave different from the default behavior expected from. NET Framework. The following sample code demonstratesWhat not to do:

 

Namespace system {public static class myextensions {public static bool isnull (this object O) {return O = NULL ;}} while (! Myobject. isnull ()){... }

 

Obsolete code

If you 've been using . NET Framework For a number of years chances are you 've seen the framework versions advance and seen instances where some of the. NET Framework classes such as prior Configuration Classes have gone obsolete and you 've got Ed warnings from the compiler about it to make you aware. You may have wondered how to do that same thing with your own code. There is Obsolete Attribute that you can use to decorate your own classes and methods to indicate they are being phased out as well. if you're working independently of others, then chances are you won't need it. however, in working with a project team where you may have implemented a framework, helper classes or other conventions, it can be very helpful to use Obsolete Attribute to flag dead code that won't be used going forward. this allows them to be migrated over time rather than just deleting from your code. this is very handy as you refactor code to communicate through the compiler that a participant item is obsolete. by default the items are served up as warnings, but an optional flag can indicate if they shoshould be treated as warnings. it is worthwhile to have that setting be a configuration value so that you can enable or disable it should ss the board.

 

// Include message for compiler to present [obsolete ("this class is dead. it has been replaced by myclass3. ")] class myclass1 {//...} // include message and generate a compiler error [obsolete ("this class is dead. it has been replaced by myclass4. "), true] class myclass2 {//...}

 

Garbage Collection

If you are programming in. Net 3.5Or before you can force garbage collection throughGC. Collect (), But it is heavily advised that you do not use it unless you really know what you are doing. it is very likely you'll outguess the garbage collection system and do more harm than good. with the release of. NET Framework 4.0There are new garbage collection options and ways to control the behavior, which does make it more feasible to trigger and control. (Note: This will likely be a future article ).

Using Keyword

The using keyword has multiple uses. One lesser known is it can be used to provide automatic cleanup of disposable types. The compiler translates it inTry... finallyBehavior. I highly recommend using it whenever usingIdatareaderOrLINQ to entityData context to retrieve data from the database. The following sample code demonstrates a simple implementation whereDatareaderIs wrapped in a using statement to ensure it is disposed when its use is out of scope.

 

 
Using (idatareader reader = provider. executereader (datacmd )){//...}

 

LINQ to entities

In past articles I 've covered LINQ to SQL and more recently LINQ to entities. I wanted to offer some clarification on when to use either. predominantly for any new development It shoshould be LINQ to entities. it contains a superset of LINQ to SQL. microsoft is continuing to advance and provide more features for LINQ to entities and does not have plans to make any advancements to LINQ to SQL.

 

<Table align = "center" border = "0" cellspacing = "0" cellpadding = "0" width = "100%"> <tr> <TD valign = "TOP"> <p> when to consider LINQ to entities: </P> <ul> <li> fashioned after ORM where you have an object structure that is already acted from the physical database </LI> <li> not targeting SQL server </Li> <li> New Development </LI> </ul> </TD> <TD valign = "TOP"> <p> when to consider LINQ to SQL: </P> <ul> <li> you are already using it </LI> <li> targeting SQL Server and a 1:1 relationship between model and database </LI> </ul> </TD> </tr> </table>

 

Parallel

Historically Moore's law has allowed our applications to run faster and faster without additional effort on our part as processors increase in speed. now that speed growth is fairly flat and the trend is towards multiple core and multiple processors. in order to take advantage of multiple processors you need to think about running steps in parallel instead of sequentially. think of it similar to threading and running multiple threads, but the difference being they are also executing processing SS different processors simultaneously. microsoft released some items in the language as well as in Microsoft Visual Studio That allows you to do more parallel programming and split tasks between processors. just because it is available and can be faster doesn't mean that everything shocould be done in parallel. often times you can get different results depending upon the problem you are solving. the following sample code shows the use ofParellel. Loop in order to read text files in parallel since they are not needed sequentially

 
Foreach (string file in inputfiles) {string content = file. readalltext (File); parallel. invoke () => countcharacters (content), () => countwords (content ));}

Compiling

This is a very simple tip and shoshould go without saying, but unfortunately gets overlooked time and time again. compiling is not the same as testing no matter how much of a hurry you are in or how small of a change you 've ve made. if you don't believe me, build an email application that involves a loop. almost every time I 've seen that done the developer didn't test thoroughly and had the loop go awry and spam a whole bunch of unsuspecting recipients. additionally, the first time a system is tested with two or more concurrent users shoshould not be when it goes in to production. folks can get lazy and execute the same tests time and time again. it is important to test from multiple perspectives as well as concurrent use.

Tools: xsd2code

Xsd2code is a tool that will generate. Net classesBased on a given XSD Schema. it makes the XSD Schema in to stronugly typed objects, which makes them easier to work. as an example of use, my company has an application for filing taxes for non-profit firms. we collect all of the data necessary and then put it in the XML format dictated by the IRS. we used xsd2code to generate stronugly typed objects from the IRS schema and make it easier to build the XML necessary for electronic filing.

Tools: linqpad and linqkit

If you are doing LINQ development linqpad and linqkit can be your best friend Ds. linqpad is a tool that allows interactive query of databases using LINQ. you can drop code snippets in to the tool that will execute and show results. this helps test out LINQ statements in advance of fully building them in code. as a byproduct of how it operates it can be used for more than just a LINQ tool. it can also be used to evaluate anyC # expressionOr statement block. You can point it to your development environment and LINQ away.

Linqkit is a companion tool to linqpad and can be used with it. linqkit helps in the process of building dynamic LINQ expressions.

Tools: 7zip

7zip is a file archive tool with a high compression ratio. it can be used in desktop form for zipping and unzipping files as well as with an SDK to bring similar compress and uncompress functionality to. net Framework. I believe. net had a namespace for helping with compressed files, but 7zip does a phenomenal job with the compression.

Tools: codeplex

Most folks seem to know about codeplex, but forget over time. It is a great place to find and share resources. There is an amazing amount of stuff available.

    • Nerddinner for ASP. NET MVC
    • Xsd2code
    • Rsstoolkit
    • Ajax Control Toolkit
    • Team Foundation Server Admin Tool
    • Windows azure Guidance
    • Lower, lower, lower, more...
Summary

We have covered a variety of C # related topics. percent of them have been covered in depth in past. net nuts and bolts articles, however, this added a twist of advice and suggestions on each of them. please feel free to share additional tips and tricks with me that you 'd like to see written in a future article.

Future Columns

The topic of the next column is yet to be determined. If you have something else in participant ular that you wowould like to see explained here You cocould reach me at through http://markstrawmyer.com /.

Related Articles
    • Optional and named parameters in C # Programming
    • Working with object context in the Entity Framework
    • Joins and UI binding with the Entity Framework

Reprinted: http://www.codeguru.com/csharp/csharp/cs_misc/article.php/c17299/C-Programming-Tips-and-Tricks.htm

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.