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;
}
Generic is a class which allows the user to define classes and methods with the placeholder.
A generic type is a generic class or interface that is parameterized over types. The following Box class will be modified to demonstrate the concept.
So, to return a null or default value from a generic method we can make use default(). default(T) will return the default object of the type which is provided.
Generic collections in C# include <List> , <SortedList> , etc.
The only thing you could do is return default(T)
, which is the default value for the type T
(null
for 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 a 0
that was popped or a 0
that indicates an error. Exceptions are generally the best way to go in such cases, but you could also change your method as follows:
public bool TryPop(out T value)
{
if (top >= 0)
{
value = arr[top--];
return true;
}
value = default(T);
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With