9

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

2
  • 16
    You don't. Unless you change the return type to int? (which is the same as Nullable<int>) Consuming code would then needs to handle it differently, since the return type has changed. Commented Dec 19, 2018 at 13:21
  • Non-local return? (cough) throw an exception (cough) Commented Dec 19, 2018 at 16:29

3 Answers 3

16

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Try it yourself. ?
I thought you wanted to post a link to eg. dotnetfiddle, but forgot about the link or so.
anyone else here who was trying to click on Try it yourself?
Sorry...i write that but now i delete it...because it was a bit confusing ithink.☺️
0

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
    }
}

Comments

-1

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;
}

1 Comment

How about private int? GetNull(){ return null;}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.