Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic return type in C#

Tags:

c#

generics

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;
}
like image 433
Tech Xie Avatar asked Sep 09 '10 23:09

Tech Xie


People also ask

What is generic in C?

Generic is a class which allows the user to define classes and methods with the placeholder.

What is generic type?

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.

How do I return a generic null?

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.

What are the generic collections in C#?

Generic collections in C# include <List> , <SortedList> , etc.


1 Answers

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;
}
like image 135
Trillian Avatar answered Oct 08 '22 11:10

Trillian