Was practicing Generics. Consider a stack method below. What is the best way of doing error checking other than throwing exceptions in a generic method. What if I want to return some result in this method.
public T pop()
{
if (top >= 0)
return arr[top--];
return -1 or null;
}
The only thing you could do is return
default(T), which is the default value for the typeT(nullfor reference types, zero for integral types and zeroed-fields object for other value types). However, this is generally a bad idea as you’ll have no way to distinguish between a0that was popped or a0that indicates an error. Exceptions are generally the best way to go in such cases, but you could also change your method as follows: