Monday, 21 March 2011

C# literals

Well, I guess this is something that should almost have become automatic actions not needing any further brain cycle wasting... but it's not the case, and every now and then I need to search the net for references and samples, cause I tend to get confused with what can be omitted and what not, so good point to write my own reference in an easy to locate place:

C# literals:

  • Array Declaration and Initialization:


    //the long way
    int[] numbers = new int[5] {1, 2, 3, 4, 5};

    //shorter
    int[] numbers = new int[] {1, 2, 3, 4, 5};

    //the shortest, more friendly way:
    int[] numbers = {1, 2, 3, 4, 5};




  • Object Initializers


    //Object, (well, this is so obvious, but anyway I add it here to have a complete reference)
    myPerson p = new Person(){
    Name: "xuan",
    Age: 30
    };



  • Collections initializers:


    List<int> myList = new List<int>(){1,2,3};

    List<Cat> cats = new List<Cat>
    {
    new Cat(){ Name = "Sylvester", Age=8 },
    new Cat(){ Name = "Whiskers", Age=2 },
    new Cat(){ Name = "Sasha", Age=14 }
    };


    And now, the one that I tend to have more doubts with, thinking that I'm just borrowing it from other dynamic languages, but not, this short nice syntax for Dictionaries is perfectly valid C#:



    var data = new Dictionary<string, string>
    {
    { "test", "val" },
    { "test2", "val2" }
    };


No comments:

Post a Comment