Skip to content

Instantly share code, notes, and snippets.

@mgroves
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save mgroves/11149437 to your computer and use it in GitHub Desktop.

Select an option

Save mgroves/11149437 to your computer and use it in GitHub Desktop.
void ErrorReturn(MethodInterceptionArgs args)
{
try
{
var methodInfo = args.Method as MethodInfo;
if (methodInfo == null)
return;
if (methodInfo.ReturnType == typeof(string)) // if it's string, just return a null
args.ReturnValue = null;
else if (typeof(IEnumerable).IsAssignableFrom(methodInfo.ReturnType))
args.ReturnValue = Activator.CreateInstance(methodInfo.ReturnType);
else if (methodInfo.ReturnType.IsValueType) // for value types, return default
args.ReturnValue = Activator.CreateInstance(methodInfo.ReturnType);
else if (methodInfo.ReturnType != typeof (void)) // anything else, return null
args.ReturnValue = null;
}
catch
{
// don't want any errors to take place trying to build the correct return value
// so just swallow them, and let args.ReturnValue stay whatever it is
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment