(X) Hide this
    • Login
    • Join
      • Say No Bots Generate New Image
        By clicking 'Register' you accept the terms of use .
        Login with Facebook

Tip: How to shorten your C# code?

(0 votes)
Denislav Savkov
>
Denislav Savkov
Joined Feb 11, 2008
Articles:   14
Comments:   6
More Articles
6 comments   /   posted on Sep 17, 2008
Tags:   denislav-savkov
Categories:   General

Some of the new features in C# 3.0 allow you to write shorter code that is easier to read and maintain. The following code couples have the same results.

  • Short syntax for object initialization initialization.

    C#

     

    ObjectType objectName = new ObjectType();
    objectName.PropertyName = newValue;
    objectName.PropertyName2 = newValue2;
     

     

    C#

    ObjectType objectName = new ObjectType(){ PropertyName = newValue, PropertyName2 = newValue2 };
  • Syntaxt for anonymous types

C#

SomeVeryLongNameOfType objectName = new SomeVeryLongNameOfType();

C#

var objectName = SomeVeryLongNameOfType();
  • Short syntax for collection initialization

C#

CollectionType collectionName = new CollectionType();
collectionName.Add( newItem1 );
..
collectionName.Add( newItemN );

C#

CollectionType collectionName = new CollectionType() { Item1,...,ItemN };

 

That's it!


Subscribe

Comments

  • -_-

    RE: Tip: How to shorten your C# code?


    posted by DDtMM on Sep 18, 2008 07:50

    I don't remember if it is in 3.0 or 3.5, but AutoProperties can save you a lot of time.

    Public string MyProp { get; set; }

    Also Linq can really shorten some login in a program.

  • dejo

    RE: Tip: How to shorten your C# code?


    posted by dejo on Sep 19, 2008 08:35

    Yes, Automatically implemented properties are also part of the 3.0 specification. Thanks for the reminder DDtMM.

  • -_-

    RE: Tip: How to shorten your C# code?


    posted by Rachida Dukes on Oct 06, 2008 09:20

    Very nice article about the C# 3.0.  I would like to know more about C# short cuts, can you direct me to the appropriate articles or documetation?

    Thanks,

    Rachida

  • -_-

    RE: Tip: How to shorten your C# code?


    posted by isit on Oct 17, 2008 04:33

    very nice but too brief .. thanks

  • iiordanov

    RE: Tip: How to shorten your C# code?


    posted by iiordanov on Oct 17, 2008 04:41

    Hi isit,

    Due to the big interest on this topic, we are going to write more detailed article about the ways you can shorten your C# code using shortcuts.

  • iiordanov

    RE: Tip: How to shorten your C# code?


    posted by iiordanov on Oct 17, 2008 04:53

    Hi All,

    Meanwhile, you can check out this article C# 3.0 Tutorial by Jonathan Worthington, there you can find a lot of useful things.
    Good luck!

Add Comment

Login to comment:
  *      *       
Login with Facebook