How can I return null from a function which should return an integer

Viewed 10377

I was asked in an interview how to return Null from a method with integer, double type, etc, without any output parameter.

3 Answers

You can do something like this.

You have to make int type nullable first. by using int? normally the int datatype in c# are not nullable by default so you have to explicitly convert the int //not nullable type to int? //nullable

You can do the same thing with double etc..

// the return-type is int?. So you can return 'null' value from it.
public static int? method() 
{
   return null;
}

You can also write the above method in this way:

// this is another way to convert "non-nullable int" to "nullable int".
public static Nullable<int> method()
{
   return null;
}

If the purpose is to return null value from a function whose return type is int then you can do something like this:

public static int method()
{
    Nullable<int> i = null;

    if (!i.HasValue)
        throw new NullReferenceException();
    else
        return 0;
}

public static void Main()
{
    int? i = null;
    try
    {
        i = method();
    }
    catch (NullReferenceException ex)
    {
        i = null;
    }
    finally 
    {
        // null value stored in the i variable will be available
    }
}

You would have to declare your return type as a nullable int. That way you can return an Int or null. See example below:

private int? AddNumbers(int? First, int? Second)
{
   return First + Second;
}
Related