Examples of C# Object Initializers
A selection of the various C# object initialization syntaxes:
// explicit shorthand array, C# 1.0 style
int[] numbersIntArray1 = { 4, 8, 15, 16, 23, 42 };
// two dimensional 3x2 array
int[,] numbersInt3x2Array = { { 4, 8 }, { 15, 16 }, { 23, 42 } };
// implicitly typed array
var numbersIntArray2 = new[] { 4, 8, 15, 16, 23, 42 };
// typed array with an implicitly type variable
var numbersDoubleArray = new double[] { 4, 8, 15, 16, 23, 42 };
// generic List<>
var numbersList = new List<int> { 4, 8, 15, 16, 23, 42 };
// generic HashSet<>
var numbersHashSet = new HashSet<int> { 4, 8, 15, 16, 23, 42 };
// generic Dictionary
var dictionary = new Dictionary<int, string>
{
{ 4, "four" },
{ 8, "eight" },
{ 15, "fifteen" },
{ 16, "sixteen" },
{ 23, "twenty three" },
{ 42, "fourty two" }
};
// implicitly typed array of System.Uri objects
var searchEngines = new[]
{
new Uri("http://www.google.com/"),
new Uri("http://www.bing.com/"),
new Uri("http://www.yahoo.com/")
};
// implicitly typed array of an anonymous type
var complexNumbers = new[]
{
new { Real = 4, Imaginary = 7 },
new { Real = -10, Imaginary = 3 },
};
// implicitly typed array of System.Func<> delegates
var operations = new Func<int, int>[]
{
(x => x * x),
(x => x + x)
};
// nested object initializers
var smtpClient = new SmtpClient
{
Host = "mail.example.com",
Port = 25,
Credentials = new NetworkCredential
{
UserName = "MailScheduler",
Password = @"%yI2Ei5GL0"
}
};
// implicitly typed jagged array of strings
var jaggedArray = new[]
{
new[] {"Jack", "Sayid", "Hurley", "Miles"},
new[] {"Sawyer", "Kate"}
};
// implicitly typed array of objects implementing IEnumerable<int>
var listOfLists = new IEnumerable<int>[]
{
new List<int> {4, 8, 15, 16, 23, 42},
new Collection<int> { 4, 8, 15, 16, 23, 42 },
new int[] {4, 8, 15, 16, 23, 42 }
};
Friday, 12 February 2010
blog comments powered by Disqus