So I have made a simple code, which passes two different arrays to a method, to check for Exceptions. But there is one problem - when I pass the arrays, if an exception is cached, in my Exceptions "nameof" part, it doesn't say which array was the one, what made the exception. I need to correct that. So do you have any ideas, how I can do this in my code?
public class CommonEnd
{
public bool IsCommonEnd(int[] a, int[] b)
{
ValidateArray(a);
ValidateArray(b);
return a.First() == b.First() || a.Last() == b.Last();
}
private void ValidateArray(int[] array)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array), "Array is NULL.");
}
if (array.Length == 0)
{
throw new ArgumentOutOfRangeException(nameof(array), "Array length can't be smaller that 1");
}
}
}
nameof(array)
will always just return the string array
. In order to know whether a
or b
went wrong, you can pass another parameter and use nameof
one level higher
private void ValidateArray(string which, int[] array)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array), $"Array {which} is NULL.");
}
if (array.Length == 0)
{
throw new ArgumentOutOfRangeException(nameof(array), $"Array {which} length can't be smaller that 1");
}
}
And in the calling method:
public bool IsCommonEnd(int[] a, int[] b)
{
ValidateArray(nameof(a), a);
ValidateArray(nameof(b), b);
return a.First() == b.First() || a.Last() == b.Last();
}