Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

like image 754
Haroon nasir Avatar asked May 16 '26 12:05

Haroon nasir


1 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;
}
like image 50
Rehan Shah Avatar answered May 18 '26 01:05

Rehan Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!