Click here to Skip to main content
15,887,288 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How to assign such string value (having pipe symbol)to a Integer type?

string sValue = 123|456;
Int Id = 0;
Id = sValue ;


What I have tried:

Id = Int32.TryParse(sValue);
Posted
Updated 18-Feb-22 12:20pm
v2

First remove the pipe symbol.

If this is to be two integers 123 and 456 then use String.Split Method (System) | Microsoft Docs[^]

If it is to be 123456 then use String.Replace Method (System) | Microsoft Docs[^]
 
Share this answer
 
Comments
Maciej Los 18-Feb-22 13:27pm    
5ed!
An integer is a basic, simple type: it can't store two values any more than you can own two cars and six cars simultaneously - you either own 2 cars, 6 cars, or 8 cars - but not any combination!

So trying to parse it as a number won't help unless you first decide if you want 123, 456, or 123456 and exactly what you want to do with the remaining data.

And you can't use TryParse like that either, because it doesn't accept a single parameter and return an integer, it takes two parameters and returns a bool:
C#
int Id;
if (!Int32.TryParse(sValue, out Id))
   {
   ... report a problem to teh user ...
   return;
   }
...use Id value here ...
 
Share this answer
 
v2
Comments
Maciej Los 18-Feb-22 13:27pm    
5ed!
If you would like to get 2 numbers, try this:

C#
string sValue = "123|456";

string[] snumbers =  sValue.Split(new string[]{"|"}, StringSplitOptions.RemoveEmptyEntries);

int iValue = 0;
foreach(string s in snumbers)
{
	if(Int32.TryParse(s, out iValue))
		Console.WriteLine($"{iValue} has been successfuly converted to integer!");
	else
		Console.WriteLine($"Oooppss.. {s} is not an integer value!");
}


Result:
123 has been successfuly converted to integer!
456 has been successfuly converted to integer!
 
Share this answer
 
Try this

C#
string _t = sValue.Replace("|","");
Id = Int32.TryParse(_t);
 
Share this answer
 
Comments
OriginalGriff 18-Feb-22 6:28am    
Reason for my vote of one: Do you know a version of the Int32.TryParse method that takes a single parameter and returns an integer?

https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-6.0

Please, test your code before you post it, particularly for beginners ...
_Asif_ 18-Feb-22 6:33am    
hmmm, acknowledged!

I usually test code online when I get the time, otherwise use what is present in the question and add the knowledge I have :)

But thanks anyway.
Maciej Los 18-Feb-22 13:29pm    
Please, improve your answer to avoid further down-voting.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900