C#: function that can return integer or string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C#: function that can return integer or string

I am creating a coding language in c#, and for the indexing of arrays and dictionaries, I need to have a function that returns the int value of a given string if possible, otherwise it must return the string itself. The problem is that the function doesn't know which datatype it needs to return, so i need a function that can return both integer and string. Does anyone know how to do that?

5th May 2020, 10:49 AM
somebody
somebody - avatar
7 Answers
+ 2
Function or methods can return only one data type at the time. I would suggest make different methods and call them according to condition and get the value.
5th May 2020, 11:29 AM
A͢J
A͢J - avatar
+ 2
I even found a better solution. I can use the dynamic data type. I think this will be my function: static dynamic intOrString(string str) { try { return Convert.ToInt32(str); } catch(Exception e) { return str; } }
5th May 2020, 5:13 PM
somebody
somebody - avatar
+ 2
somebody Yes it's right. I didn't knew about dynamic in C#. But your input should be string means 10 should not pass as integer. For example static void Main(string[] args) { Console.WriteLine(intOrString(10 + "")); } static dynamic intOrString(string str) { try { return Convert.ToInt32(str); } catch(Exception e) { return str; } }
5th May 2020, 5:32 PM
A͢J
A͢J - avatar
0
That's not really an option in my case, since the function is to check if the value is an int or a string, so you don't know it before you use the function. I think I'm just going to create a class with a public string datatype, a public int x and a public string y.
5th May 2020, 11:33 AM
somebody
somebody - avatar
0
AJ #Infinity Love it will return the integer 10, because no error will occur when you try to convert the value 10 + "" to an integer. 10 + "" is actually the same as "10" and is convertable to an integer. However, it will be written as a string, because you can only output text. I just tried it, I made the program print the type of the dynamic value with dynamic x = intOrString(10 + ""); Console.WriteLine(x.GetType().ToString()); The output was 'System.Int32'.
5th May 2020, 6:03 PM
somebody
somebody - avatar
0
int k; string s="12345"; bool b=int.TryParse(s,out k); if(b==true) Console.Write(k); else Console.Write(s); You can try this too..
6th May 2020, 11:54 AM
Nikhil Maroju
Nikhil Maroju - avatar
0
Yes, but then you would have to write the same code over and over. I needed one function that returns the Int32 value of the string if possible, otherwise it has to return the string. I already found how to do that.
6th May 2020, 6:40 PM
somebody
somebody - avatar