Last active
December 15, 2015 12:58
-
-
Save xicalango/5263664 to your computer and use it in GitHub Desktop.
Some C#--Language extensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace Extensions | |
{ | |
public static class Extensions | |
{ | |
public static void Times(this int t, Action<int> f) | |
{ | |
for (int i = 0; i < t; i++) | |
{ | |
f(i); | |
} | |
} | |
public static void Times(this int t, Action f) | |
{ | |
for (int i = 0; i < t; i++) | |
{ | |
f(); | |
} | |
} | |
public static R CallConverted<T, R>(this object o, Func<T, R> f) where T : class | |
{ | |
var converted = o as T; | |
if (converted != null) | |
{ | |
return f(converted); | |
} | |
else | |
{ | |
return default(R); | |
} | |
} | |
public static void CallConverted<T>(this object o, Action<T> f) where T : class | |
{ | |
var converted = o as T; | |
if (converted != null) | |
{ | |
f(converted); | |
} | |
} | |
public static TValue GetOrCreateValue<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TKey, TValue> createFn) | |
{ | |
TValue value = default(TValue); | |
if (dict.TryGetValue(key, out value)) | |
{ | |
return value; | |
} | |
else | |
{ | |
value = createFn(key); | |
dict[key] = value; | |
return value; | |
} | |
} | |
public static bool NullAndConditionCheck<T>(T t, Func<T, bool> f) where T : class | |
{ | |
if (t != null) | |
{ | |
return f(t); | |
} | |
else | |
{ | |
return false; | |
} | |
} | |
public static T GetExistingOrCreateNew<T>(T t, Func<T> f) where T : class | |
{ | |
if (t != null) | |
return t; | |
else return f(); | |
} | |
public static void OpenPathForReading(this string s, Action<System.IO.StreamReader> f) | |
{ | |
using (var inputStream = new System.IO.StreamReader(s)) | |
{ | |
f(inputStream); | |
} | |
} | |
public static void OpenPathForWriting(this string s, Action<System.IO.StreamWriter> f) | |
{ | |
using (var outputStream = new System.IO.StreamWriter(s)) | |
{ | |
f(outputStream); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment