Set properties faster in C♯
Recently I rediscovered that C♯ lets you set multiple properties when you create an instance of an object. I've been finding it useful, so I thought that I'd share it here.
Consider this code:
StreamWriter outgoingData = new StreamWriter("rockets.txt");
outgoingData.AutoFlush = true;
outgoingData.Encoding = Encoding.UTF8;
In the above I create a new StreamWriter
and attach it to the file rockets.txt
. I also turn on AutoFlush, and set the encoding to UTF8. The code above is starting to look a little messy, so let's rewrite it:
StreamWriter outgoingData = new StreamWriter("rockets.txt") {
AutoFlush = true,
Encoding = Encoding.UTF8
};
This technique can come in particularly handy when you need to set a lot of properties on an object upon it's creation.You can also do it with other types, too:
string[] animals = new string[] { "cat", "mouse", "elephant" };
List<int> primes = new List<int>() { 2, 3, 5, 7, 11, 13, 17, 19 };
Dictionary<string, IPAddress> ips = new Dictionary<string, IPAddress>() {
{ "google.com", Dns.GetHostAddresses("google.com")[0] }
{ "wikipedia.org", Dns.GetHostAddresses("wikipedia.org")[0] }
{ "starbeamrainbowlabs.com", Dns.GetHostAddresses("starbeamrainbowlabs.com")[0] }
{ "hull.ac.uk", Dns.GetHostAddresses("hull.ac.uk")[0] }
}