Use different ways to initialize an object in CSharp

Description

The following code shows how to use different ways to initialize an object.

Example


/*w w  w. j  a va 2 s. c  o m*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
public class Person
{
    public int Age { get; set; }
    public string Name { get; set; }

    List<Person> friends = new List<Person>();
    public List<Person> Friends
    {
        get { return friends; }
    }

    public Person()
    {
    }

    public Person(string name)
    {
        Name = name;
    }
}
class MainClass
{
    static void Main()
    {
        Person tom = new Person
        {
            Name = "Tom",
            Age = 4,
            Friends = {                                                  
                    new Person { Name = "A" },                
                    new Person("B"),                             
                    new Person { Name = "E", Age = 4 },        
                    new Person("B"){                                              
                        Age = 4,                              
                    }                                              
                }
        };
        Console.WriteLine(tom.Name);
        Console.WriteLine(tom.Age);
        Console.WriteLine(tom.Friends[0].Name);
        Console.WriteLine(tom.Friends[1].Name);
        Console.WriteLine(tom.Friends[2].Name);
        Console.WriteLine(tom.Friends[2].Age);
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var