A few helper methods in C#
Just a few methods I find myself using in a lot of projects...
Usage:
I find it much more expressive to use this ForEach extension method instead of a foreach loop:
rather than
It's probably just a quirk of mine, but I prefer it.
Good when you need to (de)serialize pesky objects. Usage:
- public static int ConvertToInt(this string value, int def)
- {
- int result;
- return Int32.TryParse(value, out result) ? result : def;
- }
- public static int ConvertToInt(this string value)
- {
- return ConvertToInt(value, -1);
- }
Usage:
- string s = "123";
- Console.WriteLine(s.ConvertToInt());
- public static void ForEach<T>(this IEnumerable<T> set, Action<T> action)
- {
- Debug.Assert(set != null, "set");
- Debug.Assert(action != null, "action");
- foreach (var item in set)
- action(item);
- }
- public static void ForEach(this IEnumerable set, Action<object> action)
- {
- Debug.Assert(set != null, "set");
- Debug.Assert(action != null, "action");
- foreach (var item in set)
- action(item);
- }
I find it much more expressive to use this ForEach extension method instead of a foreach loop:
- list.ForEach(item => { ... do something with item ... });
rather than
- foreach(var item in list)
- { ... do something with item ... }
It's probably just a quirk of mine, but I prefer it.
- public static string AsXML(this object obj)
- {
- if (obj == null)
- return "<NULL />";
- string str;
- Encoding utf8 = new UTF8Encoding();
- var objType = obj.GetType();
- var xmlatt = (XmlTypeAttribute) Attribute.GetCustomAttribute(objType, typeof (XmlTypeAttribute));
- using (var ms = new MemoryStream())
- using (var x = new XmlTextWriter(ms, utf8) {Formatting = Formatting.Indented})
- {
- var xs = xmlatt == null ? new XmlSerializer(objType) : new XmlSerializer(objType, xmlatt.Namespace);
- xs.Serialize(x, obj);
- str = utf8.GetString(ms.GetBuffer(), 0, (int) ms.Length);
- }
- return str;
- }
- public static object AsObject(this string xml, Type type)
- {
- using (var sr = new StringReader(xml))
- return new XmlSerializer(type).Deserialize(sr);
- }
- public static T As<T>(this string xml) where T : class
- {
- return xml.AsObject(typeof (T)) as T;
- }
Good when you need to (de)serialize pesky objects. Usage:
- MyClass x = new MyClass();
- string s = x.AsXML();
- x = s.As<MyClass>();
Comments