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;
}
4 Comments
Rand Random
Try it yourself. ?Rand Random
I thought you wanted to post a link to eg. dotnetfiddle, but forgot about the link or so.
Impostor
anyone else here who was trying to click on
Try it yourself?Rehan Shah
Sorry...i write that but now i delete it...because it was a bit confusing ithink.☺️
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
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
Impostor
How about
private int? GetNull(){ return null;}
int?(which is the same asNullable<int>) Consuming code would then needs to handle it differently, since the return type has changed.