- Home /
C# return question
How can I return two different types? (I am new to C#, used to JS) Example:
public static bool Test(bool s) {
if (s)
return true;
else
return;
}
you've defined the return type as an int
so need to return one. true/false are of type bool
- you cannot return that!
if you want to return different types, then choose something with a common base class. in your example, there isn't one... what are you trying to do?
Yeah, I know bad example but if it was bool I still can't use the bottom return since it would return null if I am not mistaking.
you could have nullable bool as your return type:
bool? test(bool b){
if(b){
return true;
}else{
return null;
}
}
the same would work for int? I believe, perhaps that is useful, you can't have complete seperate return types int or bool for example, as on compile the code needs to know what type to expect!
Thanks @Scribe!
I found out that I couldn't use "return;" I had to use "return null;"
Answer by DanSuperGP · Jan 09, 2015 at 06:20 PM
You cannot have more than one return type, your method must return the type specified.
if your method returns a value type it must return a value. If your method returns a reference type it must return a reference to that type (or a derived class of that type) or null.
If you are trying to return more than one value from a method you can do this several ways. You can make a class or struct that contains multiple values and return that instead. Or you can use ref or out parameters.
This tutorial should tell you what you need to know about using ref and out.