Created
January 27, 2011 20:30
-
-
Save juanplopes/799191 to your computer and use it in GitHub Desktop.
This file contains 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
public class ParamsExtraction | |
{ | |
Group group; | |
public ParamsExtraction(Group group) | |
{ | |
this.group = group; | |
} | |
private bool TryGet<T>(int position, out T result) | |
{ | |
if (!group.Success) return Failure(out result); | |
if (position >= group.Captures.Count) return Failure(out result); | |
var str = group.Captures[position].Value; | |
if (IsNonStringNullValue<T>(str)) return Failure(out result); | |
var type = typeof(T).GetValueTypeIfNullable(); | |
result = (T)Convert.ChangeType(str, type); | |
return true; | |
} | |
private static bool Failure<T>(out T result) | |
{ | |
result = default(T); | |
return false; | |
} | |
private static bool IsNonStringNullValue<T>(string str) | |
{ | |
return (typeof(T) != typeof(string) && str.Trim().IsNullOrEmpty()); | |
} | |
public T Required<T>(int position) | |
{ | |
T result; | |
if (!TryGet(position, out result)) | |
throw new ArgumentOutOfRangeException("required positional parameter {0} not found".AsFormat(position)); | |
return result; | |
} | |
public T Optional<T>(int position) | |
{ | |
T result; | |
TryGet(position, out result); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment