locked
Val() in C# RRS feed

  • Question

  • What is the equivalent in C# to the Val() function in Visual Basic? Also, what do the Right() and Left() functions do?

    Here is my code:

    Dim Num As Byte
    Dim File As String
    Num = Val(Right(Left(Right(File, Len(File) - i), 8), 3))

    Saturday, April 17, 2010 11:42 PM

Answers

  • The Left and Right in VB pull of the left and right characters.

    So working from the inside out, the Right pulls the right characters from the File string up to the length of the file string - i. Then it takes the left 8 characters of that. Then the right 3.

    I assume that the file string in tihs case had some type of number embedded in it and that was the way the VB code pulled the number from the string.

    VB.NET has a substring feature that might be easier to use for this.

    The Val converts the resulting number within the string to a number. There are numerous ways to do this in VB.NET including the code that Crazed Potatoe posted. Another way is to use TryParse. It helps handle the case where you end up with a string that is not a valid number.

          string s = "12";
          int num;
          if (int.TryParse(s, out num))
          {
    
          }

    Hope this helps.


    www.insteptech.com ; msmvps.com/blogs/deborahk
    We are volunteers and ask only that if we are able to help you, that you mark our reply as your answer. THANKS!
    • Marked as answer by Liliane Teng Thursday, April 22, 2010 6:24 AM
    Sunday, April 18, 2010 1:22 AM
  • If you want to convert a string into an integer value, you got this function:

     

    // Dim X As Integer <--- Visual Basic
    
    int X;
    
    X = System.Convert.ToInt32("500");

    Now the variable X should be 500. If there is any "non-number" in the stirng, you will receive an runtime-error.

     

    If you mean receiving a numeric value from a specific posistion of a string:

     

    string myString = "TEST 200 TEST";
    
    // myString[5] = 2 myString[6] = 0 myString[7] = 0
    
    int X = System.Convert.ToInt32(myString[5] + myString[6] + myString[7]);

     

    Now X should be 200. the "non-number" runtim-error also applies here, since it uses the same function.

    • Marked as answer by Liliane Teng Thursday, April 22, 2010 6:24 AM
    Sunday, April 18, 2010 12:28 AM
  • Right & Left are NOT bitwise operations.

    Right - "Returns a string containing a specified number of characters from the right side of a string."

    http://msdn.microsoft.com/en-us/library/dxs6hz0a(VS.80).aspx

    Left - "Returns a string containing a specified number of characters from the left side of a string."

    http://msdn.microsoft.com/en-us/library/y050k1wb(VS.80).aspx

     

    Both Right and Left can be done with String.Substring()

     

    Val - "Returns the numbers contained in a string as a numeric value of appropriate type."

    http://msdn.microsoft.com/en-us/library/k7beh1x9(VS.80).aspx
    make sure to read the remarks though.

    As far as I know there is no c# equivalent for this one, but, as Crazed Potatoe said the closest ones are Convert.ToDouble(), Double.Parse() and Double.TryParse() (you can use the numeric appropriate type instead of double).

    EDIT: And if I'm not mistaken here,
    Right(Left(Right(File, Len(File) - i), 8), 3)
    is the same as
    Right(Left(File, i + 8), 3)
    and c# would be
    string s = File.Substring(i + 5, 3);

     

    Best regards, 
    Vladimir

    • Marked as answer by Liliane Teng Thursday, April 22, 2010 6:24 AM
    Sunday, April 18, 2010 1:33 AM
  • "Left" and "Right" are easy:

    x = Left(y, 2) converts to x = y.Substring(0, 2);

    x = Right(y, 2) converts to x = y.Substring(y.Length - z);

    "Val" has no direct equivalent - the Microsoft.VisualBasic.Conversion.Val function attempts to derive a numeric value from an object and will make an attempt where other approaches produce an exception.

     


    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    • Marked as answer by Liliane Teng Thursday, April 22, 2010 6:24 AM
    Sunday, April 18, 2010 2:40 PM

All replies

  • Hey there :)

     

    The byte and file variable are easy to make:

     

    byte Num;
    string File;

    The Val() function is just a normal number, you can either write Val(5), or 5 in Visual Baisc.

    In C# you must write 5 instead of Val(5).

     

    Hope this will help you :]

    Saturday, April 17, 2010 11:49 PM
  • All of that is helpful, but what exactly is the Val() function meant to do?
    Sunday, April 18, 2010 12:09 AM
  • The Val() function is just a normal integer number, you can either write Val(5), or 5 in Visual Baisc.

    In C# you must write 5 instead of Val(5).

    Sunday, April 18, 2010 12:11 AM
  • So how does it get an integer from a string type?
    Sunday, April 18, 2010 12:19 AM
  • If you want to convert a string into an integer value, you got this function:

     

    // Dim X As Integer <--- Visual Basic
    
    int X;
    
    X = System.Convert.ToInt32("500");

    Now the variable X should be 500. If there is any "non-number" in the stirng, you will receive an runtime-error.

     

    If you mean receiving a numeric value from a specific posistion of a string:

     

    string myString = "TEST 200 TEST";
    
    // myString[5] = 2 myString[6] = 0 myString[7] = 0
    
    int X = System.Convert.ToInt32(myString[5] + myString[6] + myString[7]);

     

    Now X should be 200. the "non-number" runtim-error also applies here, since it uses the same function.

    • Marked as answer by Liliane Teng Thursday, April 22, 2010 6:24 AM
    Sunday, April 18, 2010 12:28 AM
  • The Left and Right in VB pull of the left and right characters.

    So working from the inside out, the Right pulls the right characters from the File string up to the length of the file string - i. Then it takes the left 8 characters of that. Then the right 3.

    I assume that the file string in tihs case had some type of number embedded in it and that was the way the VB code pulled the number from the string.

    VB.NET has a substring feature that might be easier to use for this.

    The Val converts the resulting number within the string to a number. There are numerous ways to do this in VB.NET including the code that Crazed Potatoe posted. Another way is to use TryParse. It helps handle the case where you end up with a string that is not a valid number.

          string s = "12";
          int num;
          if (int.TryParse(s, out num))
          {
    
          }

    Hope this helps.


    www.insteptech.com ; msmvps.com/blogs/deborahk
    We are volunteers and ask only that if we are able to help you, that you mark our reply as your answer. THANKS!
    • Marked as answer by Liliane Teng Thursday, April 22, 2010 6:24 AM
    Sunday, April 18, 2010 1:22 AM
  • Right & Left are NOT bitwise operations.

    Right - "Returns a string containing a specified number of characters from the right side of a string."

    http://msdn.microsoft.com/en-us/library/dxs6hz0a(VS.80).aspx

    Left - "Returns a string containing a specified number of characters from the left side of a string."

    http://msdn.microsoft.com/en-us/library/y050k1wb(VS.80).aspx

     

    Both Right and Left can be done with String.Substring()

     

    Val - "Returns the numbers contained in a string as a numeric value of appropriate type."

    http://msdn.microsoft.com/en-us/library/k7beh1x9(VS.80).aspx
    make sure to read the remarks though.

    As far as I know there is no c# equivalent for this one, but, as Crazed Potatoe said the closest ones are Convert.ToDouble(), Double.Parse() and Double.TryParse() (you can use the numeric appropriate type instead of double).

    EDIT: And if I'm not mistaken here,
    Right(Left(Right(File, Len(File) - i), 8), 3)
    is the same as
    Right(Left(File, i + 8), 3)
    and c# would be
    string s = File.Substring(i + 5, 3);

     

    Best regards, 
    Vladimir

    • Marked as answer by Liliane Teng Thursday, April 22, 2010 6:24 AM
    Sunday, April 18, 2010 1:33 AM
  • "Left" and "Right" are easy:

    x = Left(y, 2) converts to x = y.Substring(0, 2);

    x = Right(y, 2) converts to x = y.Substring(y.Length - z);

    "Val" has no direct equivalent - the Microsoft.VisualBasic.Conversion.Val function attempts to derive a numeric value from an object and will make an attempt where other approaches produce an exception.

     


    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    • Marked as answer by Liliane Teng Thursday, April 22, 2010 6:24 AM
    Sunday, April 18, 2010 2:40 PM
  •  private int Val(string p_Val)
            {
                if (p_Val.Trim() == "")
                    return 0;
                char[] cRec = p_Val.ToCharArray();
                string sNum = string.Empty;
                for (int i = 0; i < cRec.Length; i++)
                {
                    if (char.IsNumber(cRec[i]))
                        sNum += cRec[i];
                    else
                    {
                        if (sNum != "")
                        {
                            try
                            {
                                return Convert.ToInt32(sNum);
                            }
                            catch
                            {
                                return 0;
                            }
                        }
                        return 0;
                    }
                }
                return 0;
            }
    Friday, February 10, 2012 3:26 PM
  • Close but no cigar.... try this

       private int Val(string p_Val)
        {
          if (p_Val.Trim() == "")
            return 0;
          char[] cRec = p_Val.ToCharArray();
          string sNum = string.Empty;
          for (int i = 0; i < cRec.Length; i++)
          {
            if (char.IsNumber(cRec[i]))
              sNum += cRec[i];
            else
            {
              if (sNum != "")
              {
                try
                {
                  return Convert.ToInt32(sNum);
                }
                catch
                {
                  return 0;
                }
              }
            }
          }
          try
          {
            return Convert.ToInt32(sNum);
          }
          catch
          {
            return 0;
          }
        }

    • Proposed as answer by MDooney Saturday, July 7, 2012 4:17 PM
    Saturday, July 7, 2012 4:17 PM
  • Close but no cigar.... try this

       private int Val(string p_Val)
        {
          if (p_Val.Trim() == "")
            return 0;
          char[] cRec = p_Val.ToCharArray();
          string sNum = string.Empty;
          for (int i = 0; i < cRec.Length; i++)
          {
            if (char.IsNumber(cRec[i]))
              sNum += cRec[i];
            else
            {
              if (sNum != "")
              {
                try
                {
                  return Convert.ToInt32(sNum);
                }
                catch
                {
                  return 0;
                }
              }
            }
          }
          try
          {
            return Convert.ToInt32(sNum);
          }
          catch
          {
            return 0;
          }
        }

    There are a number of problems with this post.

    1. You're responding to a two year old thread that has already been answered.  If you would like to be helpful and answer questions it would be more beneficial to answer questions asked within the past few days that have not already been answered.
    2. You should not propose your own posts as the answer.  Obviously you think it is the answer or you wouldn't have posted it.  Proposing a post as the answer is a mechanism for someone else to agree with you and say that the post ought to be marked as the answer without cluttering up the thread with spammy "I agree" posts.
    3. You shouldn't use exceptions for flow control.  You should validate the input properly to ensure that exceptions don't occur in the valid cases and exceptions are only thrown when there is no way for you to prevent them.  In this case, it would be better to just use the int.TryParse method to prevent any possible exceptions when parsing the result.
    4. You should not return 0 when you fail to parse an integer.  0 is a valid result, and there's no way to distinguish an actual 0 from the case where the input was invalid.
    5. Your code doesn't handle inputs with decimals or thousands separators, nor does it handle the different cultures that could be used for them.
    6. You don't need to convert a string to a char array.  It already has a indexer to access the characters, and it also implements IEnumerable<char>.  Between those two you can do everything you're doing to the array to the string itself.
    • Proposed as answer by codertuhin Thursday, October 23, 2014 6:22 AM
    • Unproposed as answer by codertuhin Thursday, October 23, 2014 6:22 AM
    Monday, July 9, 2012 1:57 PM
  • if (int.TryParse(textbox1.Text, out numberoforder))
                    ItemChickenB = Val(textbox1.Text);
                MealCostB = BaconCheeseCost * ItemBaconCheese;
                MealCostC = MealCostF + MealCostB + MealCostD;

    how about in these codes? what can i use as alternative in val? im only using c# 2005

    Sunday, January 8, 2017 3:00 AM
  • Do you expect textbox1.Text to be an int?  If so, then you already have it - just use the 'numberoforder' value instead of getting "Val(textbox1.Text)".

    If you expect it to be something else, such as double, then use that type's 'TryParse' and use the 'out' value (i.e., your 'numberoforder' variable).

    If you want to reproduce the quirkiness of VB's 'Val' operator more closely, you can use the helper class that our converter inserts for this purpose:

    public static partial class Simulate
    {
    	public static double Val(string expression)
    	{
    		if (expression == null)
    			return 0;
    
    		//try the entire string, then progressively smaller
    		//substrings to simulate the behavior of VB's 'Val',
    		//which ignores trailing characters after a recognizable value:
    		for (int size = expression.Length; size > 0; size--)
    		{
    			double testDouble;
    			if (double.TryParse(expression.Substring(0, size), out testDouble))
    				return testDouble;
    		}
    
    		//no value is recognized, so return 0:
    		return 0;
    	}
    	public static double Val(object expression)
    	{
    		if (expression == null)
    			return 0;
    
    		double testDouble;
    		if (double.TryParse(expression.ToString(), out testDouble))
    			return testDouble;
    
    		//VB's 'Val' function returns -1 for 'true':
    		bool testBool;
    		if (bool.TryParse(expression.ToString(), out testBool))
    			return testBool ? -1 : 0;
    
    		//VB's 'Val' function returns the day of the month for dates:
    		System.DateTime testDate;
    		if (System.DateTime.TryParse(expression.ToString(), out testDate))
    			return testDate.Day;
    
    		//no value is recognized, so return 0:
    		return 0;
    	}
    	public static int Val(char expression)
    	{
    		int testInt;
    		if (int.TryParse(expression.ToString(), out testInt))
    			return testInt;
    		else
    			return 0;
    	}
    }
    You may need something newer than VS 2005 - that's 12 years old, which is an eternity in the tech world - what's stopping you from upgrading?  (VS Community 2015 is free).


    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter


    Sunday, January 8, 2017 3:31 AM