User Tools

Site Tools


technical_notes:public:20131015-cs-cookbook

Parent

C# - Cookbook

Some recipes on C#.

Enum

How to use an enum as a flags ?

[Flags]
internal enum ContentType
{
	Header = 0x1,
	Content = 0x2,
	Footer = 0x4,
}
 
internal class Program
{
	private static void Main(string[] args)
	{
		ContentType type = ContentType.Header;
		type |= ContentType.Content;
 
		if ((type & ContentType.Header) == ContentType.Header)
		{
			Console.Out.WriteLine("Header");
		}
	}
}

You have to set value manually on enum to avoid overlapped values.

Resources :

How to transform text in Enum ?

I can see 3 solutions :

  • Using condition as if or switch on each value
  • Using Enum.TryParse (Easy, be careful with performance)
  • Using Dictionary
var enumTranslator = new Dictionary<string, ContentType>()
{
    {"Header", ContentType.Header},
    {"Content", ContentType.Content},
    {"Footer", ContentType.Footer}
};
 
foreach (var content in contents)
{
    if (!enumTranslator.ContainsKey(content.Type))
    {
        _log.DebugFormat("Entity inconnue - {0}", entity.Type);
        continue;
    }
 
    ContentType type = enumTranslator[content];
}

Generic

How to check an item implement a specific generic ?

if (messageType.IsGenericType &&
    messageType.GetGenericTypeDefinition() == typeof(SpecificGeneric<>))
{
  // Do something
}

How to declare an object as instanciable ?

internal class Converter
{
    public static T Convert<C, T>(T value)
        where C : IValueConverter, new()
    {
        C converter = new C();
        return (T)converter.Convert(value, typeof(T), null, CultureInfo.InvariantCulture);
    }
}   

Interface

Rule 1 : An interface rely mainly on other interface (think to IList or IDictionary)

LINQ

How to sort a List<> or IList<> ?

IList<Item> list = new List<Item>() { new Item() {Label="test2"}, new Item() {Label="test1"}};
var list_sorted = list.OrderBy(i => i.Label).ToList();

String

How to replace french accent by Ascii characters in a string ?

How to set a generic method with type you can instanciate ?

public TResult Execute<TResult>() where TResult:new()
{
  // ...
}

Process

How to send key input to a process ?

[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
 
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
    SetForegroundWindow(p.MainWindowHandle);
    SendKeys.SendWait("{DOWN}");
}

Resources :

technical_notes/public/20131015-cs-cookbook.txt · Last modified: 2013/12/09 15:49 by Fabien Arcellier