Thursday, March 23, 2017

C# Things I've Been Learning Lately


How to iterate over Enum types:
foreach (var myType in 
   Enum.GetValues(typeof(MyType)).Cast<MyType>())
{
...
}

How to create a case-insensitive dictionary with a "string" key and a "MyType" value.
private static readonly Dictionary< string, MyType> _dictionary = 
  new Dictionary<string, MyType>(StringComparer.InvariantCultureIgnoreCase);
The Dictionary class takes an optional parameter of IEqualityComparer<tkey>. By passing in "StringComparer.InvariantCultureIgnoreCase" you create a dictionary that is case-insensitive for the string keys.
How to capitalize the first letter of each word in a string? String functions "ToUpper()" and "ToLower()" have a cousin, "ToTitleCase()" that capitalizes the first letter in each word
System.Globalization.TextInfo textInfo = 
        new System.Globalization.CultureInfo("en-US", false).TextInfo;
title = textInfo.ToTitleCase("we hold tHese tRuths tO be Self evident"); 
//We Hold These Truths To Be Self Evident

How to read data from an embedded file? First add the file to your project and set its Property "Build Action" to "Embedded Resource".
var assembly = Assembly.GetExecutingAssembly();
var name = assembly.GetName().Name;
var resourceName = $"{name}.MyTextFile.txt";

using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();
     ...
        }
    }
}

No comments: