Comparing values using == operator - c#

I have a static method which simply compares two values and returns the result
public class Calculator
{
public static bool AreEqual(object value1, object value2)
{
return value1 == value2;
}
}
bool Equal = Calculator.AreEqual("a", "a"); // returns true
bool Equal = Calculator.AreEqual(1, 1); // returns false
Can someone please explain what is going on behind the scenes that produces the output described above

The runtime identifies your literal usages of "a" and retrieves the same reference to all those usages, resulting in one string object rather than two as you would expect.
Instead of using literals, try the following:
string A1 = new string(new char[] {'a'});
string A2 = new string(new char[] {'a'});
Calculator.AreEqual(A1, A2); // returns false
What you've presented here is known as string interning.
You can find more information in the String.Intern method page.

Related

string interning and referenceEquals

I'm trying to understand string interning. Not for any real purpose other than learning.
Here's where I'm at:
Strings are immutable and a reference type. Its this immutability that allows us to do string interning.
Without string interning, the two strings will be two strings on the heap.
e.g.
private static void Main()
{
var a = "foo";
var b = "foo";
ReferenceEquals(a, b); // would expect this to be false...
}
I would expect that ReferenceEquals to be false. It isn't though it's true. I thought to make it true I would have to do:
private static void Main()
{
var a = "foo";
var b = "foo";
ReferenceEquals(a, b); // false??
string.Intern(a);
string.Intern(b);
ReferenceEquals(a, b); // true?
}
Since the interning process, as I understand it, looks for the string in a hash table and if its not there it adds it. On further interning it looks for the string and if it finds it, then it changes the reference to point to the same place in the hash table.
This should speed up comparisons? Since it it doesn't need to check if each char matches and can just check if both strings point to the same location. (Let's ignore the overhead of actually interning for now till I understand how this works).
So what am I not getting. Why is the first code block returning true and not false?
This occurs because "foo" is interned.
static void Main(string[] args)
{
var a = "foo";
var b = "foo";
Console.WriteLine(string.IsInterned(a));
Console.WriteLine(ReferenceEquals(a, b));
Console.ReadLine();
}
The compiler will intern all literals / constants by default.

Check if string is numeric in one line of code

I'm working with a DNN form-building module that allows for some server-side code to be run based on a condition. For my particular scenario, I need my block of code to run if the first 4 characters of a certain form text are numeric.
The space to type the condition, though, is only one line and I believe gets injected into an if statement somewhere behind the scenes so I don't have the ability to write a mult-line conditional.
If I have a form field called MyField, I might create a simple conditional like this:
[MyField] == "some value"
Then somewhere behind the scenes it gets translated to something like if("some value" == "some value") {
I know that int.TryParse() can be used to determine whether or not a string is numeric but every implementation I've seen requires two lines of code, the first to declare a variable to contain the converted integer and the second to run the actual function.
Is there a way to check to see if the first 4 characters of a string are numeric in just one line that can exist inside an if statement?
Wrap it in an extension method.
public static class StringExtensions
{
public static bool IsNumeric(this string input)
{
int number;
return int.TryParse(input, out number);
}
}
And use it like
if("1234".IsNumeric())
{
// Do stuff..
}
UPDATE since question changed:
public static class StringExtensions
{
public static bool FirstFourAreNumeric(this string input)
{
int number;
if(string.IsNullOrEmpty(input) || input.Length < 4)
{
throw new Exception("Not 4 chars long");
}
return int.TryParse(input.Substring(4), out number);
}
}
And use it like
if("1234abc".FirstFourAreNumeric())
{
// Do stuff..
}
In response to this:
Is there a way to check to see if the first 4 characters of a string are numeric in just one line that can exist inside an if statement?
You guys don't have to make it account for anything more complicated than a positive integer.
new Regex(#"^\d{4}").IsMatch("3466") // true
new Regex(#"^\d{4}").IsMatch("6") // false
new Regex(#"^\d{4}").IsMatch("68ab") // false
new Regex(#"^\d{4}").IsMatch("1111abcdefg") // true
// in an if:
if (new Regex(#"^\d{4}").IsMatch("3466"))
{
// Do something
}
Old answer:
If you can't use TryParse, you could probably get away with using LINQ:
"12345".All(char.IsDigit); // true
"abcde".All(char.IsDigit); // false
"abc123".All(char.IsDigit); // false
If you can, here's an IsNumeric extension method, with usage:
public static class NumberExtensions
{
// <= C#6
public static bool IsNumeric(this string str)
{
float f;
return float.TryParse(str, out f);
}
// C# 7+
public static bool IsNumeric(this string str) => float.TryParse(str, out var _);
}
// ... elsewhere
"123".IsNumeric(); // true
"abc".IsNumeric(); // false, etc
"-1.7e5".IsNumeric(); // true
How about some easy LinQ?
if (str.Take(4).All(char.IsDigit) { ... }

Comparing 2 reference strings returns true [duplicate]

This question already has answers here:
Intern string literals misunderstanding?
(2 answers)
Closed 6 years ago.
string a = "abc";
string b = "abc";
Console.WriteLine(String.ReferenceEquals(a, b));
a and b are CLEARLY different references, yet, I get true. Why is this? Somewhere I've read that when you assign abc to b, the compiler sees that there's already the exact abc value in the heap and points to the same memory address as a, but if this was the case, then by that logic the last line of this code below should print true:
class SomeClass
{
public int _num;
public SomeClass(int num)
{
_num = num;
}
}
var a = new SomeClass(3);
var b = new SomeClass(3);
Console.WriteLine(Object.ReferenceEquals(a, b)); // prints false
a and b are CLEARLY different references.
No, they are not. That string is interned.
The 'catch' with strings in general is that == calls the string.Equals method, which does not only compare references, but also the actual representation of the string.
Proof:
string a = "a";
string b = "a"; // intering
string c = new string(a.ToCharArray()); // no interning
bool r;
r = a == b; // true: references the same
r = a == c; // true: references different, match string value
r = (object)a == (object)b; // true: references the same
r = (object)a == (object)c; // false: references different
In the compilation step, string literals are pooled and all references to a specific value will be equal.
From the specifications (boldface mine):
Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (Section 7.9.7) appear in the same assembly, these string literals refer to the same string instance.

Assign values of array to separate variables in one line

Can I assign each value in an array to separate variables in one line in C#? Here's an example in Ruby code of what I want:
irb(main):001:0> str1, str2 = ["hey", "now"]
=> ["hey", "now"]
irb(main):002:0> str1
=> "hey"
irb(main):003:0> str2
=> "now"
I'm not sure if what I'm wanting is possible in C#.
Edit: for those suggesting I just assign the strings "hey" and "now" to variables, that's not what I want. Imagine the following:
irb(main):004:0> val1, val2 = get_two_values()
=> ["hey", "now"]
irb(main):005:0> val1
=> "hey"
irb(main):006:0> val2
=> "now"
Now the fact that the method get_two_values returned strings "hey" and "now" is arbitrary. In fact it could return any two values, they don't even have to be strings.
This is not possible in C#.
The closest thing I can think of is to use initialization in the same line with indexs
strArr = new string[]{"foo","bar"};
string str1 = strArr[0], str2 = strArr[1];
Update: In C#7 you can easily assign multiple variables at once using tuples. In order to assign array elements to variables, you'd need to write an appropriate Deconstruct() extension methods:
Another way to consume tuples is to deconstruct them. A deconstructing
declaration is a syntax for splitting a tuple (or other value) into
its parts and assigning those parts individually to fresh variables:
(string first, string middle, string last) = LookupName(id1); // deconstructing declaration
WriteLine($"found {first} {last}.");
In a deconstructing declaration you can use var for the individual
variables declared:
(var first, var middle, var last) = LookupName(id1); // var inside
Or even put a single var outside of the parentheses as an
abbreviation:
var (first, middle, last) = LookupName(id1); // var outside
You can also deconstruct into existing variables with a deconstructing
assignment:
(first, middle, last) = LookupName(id2); // deconstructing assignment
Deconstruction is not just for tuples. Any type can be deconstructed,
as long as it has an (instance or extension) deconstructor method of
the form:
public void Deconstruct(out T1 x1, ..., out Tn xn) { ... }
The out parameters constitute the values that result from the
deconstruction.
(Why does it use out parameters instead of returning a tuple? That is
so that you can have multiple overloads for different numbers of
values).
class Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y) { X = x; Y = y; }
public void Deconstruct(out int x, out int y) { x = X; y = Y; }
}
(var myX, var myY) = GetPoint(); // calls Deconstruct(out myX, out myY);
It will be a common pattern to have constructors and deconstructors be
“symmetric” in this way.
https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
Old answer:
In fact, you can achieve similar functionality in C# by using extension methods like this (note: I haven't include checking if arguments are valid):
public static void Match<T>(this IList<T> collection, Action<T,T> block)
{
block(collection[0], collection[1]);
}
public static void Match<T>(this IList<T> collection, Action<T,T,T> block)
{
block(collection[0], collection[1], collection[2]);
}
//...
And you can use them like this:
new[] { "hey", "now" }.Match((str1, str2) =>
{
Console.WriteLine(str1);
Console.WriteLine(str2);
});
In case a return value from a function is needed, the following overload would work:
public static R Match<T,R>(this IList<T> collection, Func<T, T, R> block)
{
return block(collection[0], collection[1]);
}
private string NewMethod1()
{
return new[] { "hey", "now" }.Match((str1, str2) =>
{
return str1 + str2;
});
}
In this way:
You avoid having to repeat array name like in solution proposed by JaredPar and others; the list of "variables" is easy to read.
You avoid having to explicitly declare variables types like in Daniel Earwicker's solution.
The disadvantage is that you end up with additional code block, but I think it's worth it. You can use code snippets in order to avoid typing braces etc. manually.
I know it's a 7 years old question, but not so long time ago I needed such a solution - easy giving names to array elements passed into the method (no, using classes/structs instead of arrays wasn't practical, because for same arrays I could need different element names in different methods) and unfortunately I ended up with code like this:
var A = points[0];
var A2 = points[1];
var B = points[2];
var C2 = points[3];
var C = points[4];
Now I could write (in fact, I've refactored one of those methods right now!):
points.Match((A, A2, B, C2, C) => {...});
My solution is similar to pattern matching in F# and I was inspired by this answer: https://stackoverflow.com/a/2321922/6659843
The real-world use case for this is providing a convenient way to return multiple values from a function. So it is a Ruby function that returns a fixed number of values in the array, and the caller wants them in two separate variables. This is where the feature makes most sense:
first_name, last_name = get_info() // always returns an array of length 2
To express this in C# you would mark the two parameters with out in the method definition, and return void:
public static void GetInfo(out string firstName, out string lastName)
{
// assign to firstName and lastName, instead of trying to return them.
}
And so to call it:
string firstName, lastName;
SomeClass.GetInfo(out firstName, out lastName);
It's not so nice. Hopefully some future version of C# will allow this:
var firstName, lastName = SomeClass.GetInfo();
To enable this, the GetInfo method would return a Tuple<string, string>. This would be a non-breaking change to the language as the current legal uses of var are very restrictive so there is no valid use yet for the above "multiple declaration" syntax.
You can do it in one line, but not as one statement.
For example:
int str1 = "hey"; int str2 = "now";
Python and ruby support the assignment you're trying to do; C# does not.
You can do this in C#
string str1 = "hey", str2 = "now";
or you can be fancy like this
int x, y;
int[] arr = new int[] { x = 1, y = 2 };
You can use named tuples with C# 7 now.
{
(string part1, string part2) = Deconstruct(new string[]{"hey","now"});
}
public (string, string) Deconstruct(string[] parts)
{
return (parts[0], parts[1]);
}
I'm not sure if what I'm wanting is
possible in C#.
It's not.
No, but you can initialize an array of strings:
string[] strings = new string[] {"hey", "now"};
Although that's probably not too useful for you. Frankly its not hard to put them on two lines:
string str1 = "hey";
string str2 = "now";

Identify if a string is a number

If I have these strings:
"abc" = false
"123" = true
"ab2" = false
Is there a command, like IsNumeric() or something else, that can identify if a string is a valid number?
int n;
bool isNumeric = int.TryParse("123", out n);
Update As of C# 7:
var isNumeric = int.TryParse("123", out int n);
or if you don't need the number you can discard the out parameter
var isNumeric = int.TryParse("123", out _);
The var s can be replaced by their respective types!
This will return true if input is all numbers. Don't know if it's any better than TryParse, but it will work.
Regex.IsMatch(input, #"^\d+$")
If you just want to know if it has one or more numbers mixed in with characters, leave off the ^ + and $.
Regex.IsMatch(input, #"\d")
Edit:
Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.
You can also use:
using System.Linq;
stringTest.All(char.IsDigit);
It will return true for all Numeric Digits (not float) and false if input string is any sort of alphanumeric.
Test case
Return value
Test result
"1234"
true
✅Pass
"1"
true
✅Pass
"0"
true
✅Pass
""
true
⚠️Fail (known edge case)
"12.34"
false
✅Pass
"+1234"
false
✅Pass
"-13"
false
✅Pass
"3E14"
false
✅Pass
"0x10"
false
✅Pass
Please note: stringTest should not be an empty string as this would pass the test of being numeric.
I've used this function several times:
public static bool IsNumeric(object Expression)
{
double retNum;
bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
}
But you can also use;
bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false
From Benchmarking IsNumeric Options
(source: aspalliance.com)
(source: aspalliance.com)
This is probably the best option in C#.
If you want to know if the string contains a whole number (integer):
string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);
The TryParse method will try to convert the string to a number (integer) and if it succeeds it will return true and place the corresponding number in myInt. If it can't, it returns false.
Solutions using the int.Parse(someString) alternative shown in other responses works, but it is much slower because throwing exceptions is very expensive. TryParse(...) was added to the C# language in version 2, and until then you didn't have a choice. Now you do: you should therefore avoid the Parse() alternative.
If you want to accept decimal numbers, the decimal class also has a .TryParse(...) method. Replace int with decimal in the above discussion, and the same principles apply.
You can always use the built in TryParse methods for many datatypes to see if the string in question will pass.
Example.
decimal myDec;
var Result = decimal.TryParse("123", out myDec);
Result would then = True
decimal myDec;
var Result = decimal.TryParse("abc", out myDec);
Result would then = False
In case you don't want to use int.Parse or double.Parse, you can roll your own with something like this:
public static class Extensions
{
public static bool IsNumeric(this string s)
{
foreach (char c in s)
{
if (!char.IsDigit(c) && c != '.')
{
return false;
}
}
return true;
}
}
If you want to catch a broader spectrum of numbers, à la PHP's is_numeric, you can use the following:
// From PHP documentation for is_numeric
// (http://php.net/manual/en/function.is-numeric.php)
// Finds whether the given variable is numeric.
// Numeric strings consist of optional sign, any number of digits, optional decimal part and optional
// exponential part. Thus +0123.45e6 is a valid numeric value.
// Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
// only without sign, decimal and exponential part.
static readonly Regex _isNumericRegex =
new Regex( "^(" +
/*Hex*/ #"0x[0-9a-f]+" + "|" +
/*Bin*/ #"0b[01]+" + "|" +
/*Oct*/ #"0[0-7]*" + "|" +
/*Dec*/ #"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" +
")$" );
static bool IsNumeric( string value )
{
return _isNumericRegex.IsMatch( value );
}
Unit Test:
static void IsNumericTest()
{
string[] l_unitTests = new string[] {
"123", /* TRUE */
"abc", /* FALSE */
"12.3", /* TRUE */
"+12.3", /* TRUE */
"-12.3", /* TRUE */
"1.23e2", /* TRUE */
"-1e23", /* TRUE */
"1.2ef", /* FALSE */
"0x0", /* TRUE */
"0xfff", /* TRUE */
"0xf1f", /* TRUE */
"0xf1g", /* FALSE */
"0123", /* TRUE */
"0999", /* FALSE (not octal) */
"+0999", /* TRUE (forced decimal) */
"0b0101", /* TRUE */
"0b0102" /* FALSE */
};
foreach ( string l_unitTest in l_unitTests )
Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() );
Console.ReadKey( true );
}
Keep in mind that just because a value is numeric doesn't mean it can be converted to a numeric type. For example, "999999999999999999999999999999.9999999999" is a perfeclty valid numeric value, but it won't fit into a .NET numeric type (not one defined in the standard library, that is).
I know this is an old thread, but none of the answers really did it for me - either inefficient, or not encapsulated for easy reuse. I also wanted to ensure it returned false if the string was empty or null. TryParse returns true in this case (an empty string does not cause an error when parsing as a number). So, here's my string extension method:
public static class Extensions
{
/// <summary>
/// Returns true if string is numeric and not empty or null or whitespace.
/// Determines if string is numeric by parsing as Double
/// </summary>
/// <param name="str"></param>
/// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
/// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
/// <returns></returns>
public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
CultureInfo culture = null)
{
double num;
if (culture == null) culture = CultureInfo.InvariantCulture;
return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
}
}
Simple to use:
var mystring = "1234.56789";
var test = mystring.IsNumeric();
Or, if you want to test other types of number, you can specify the 'style'.
So, to convert a number with an Exponent, you could use:
var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);
Or to test a potential Hex string, you could use:
var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)
The optional 'culture' parameter can be used in much the same way.
It is limited by not being able to convert strings that are too big to be contained in a double, but that is a limited requirement and I think if you are working with numbers larger than this, then you'll probably need additional specialised number handling functions anyway.
UPDATE of Kunal Noel Answer
stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.
But, for this case we have that empty strings will pass that test, so, you can:
if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
// Do your logic here
}
You can use TryParse to determine if the string can be parsed into an integer.
int i;
bool bNum = int.TryParse(str, out i);
The boolean will tell you if it worked or not.
If you want to know if a string is a number, you could always try parsing it:
var numberString = "123";
int number;
int.TryParse(numberString , out number);
Note that TryParse returns a bool, which you can use to check if your parsing succeeded.
I guess this answer will just be lost in between all the other ones, but anyway, here goes.
I ended up on this question via Google because I wanted to check if a string was numeric so that I could just use double.Parse("123") instead of the TryParse() method.
Why? Because it's annoying to have to declare an out variable and check the result of TryParse() before you know if the parse failed or not. I want to use the ternary operator to check if the string is numerical and then just parse it in the first ternary expression or provide a default value in the second ternary expression.
Like this:
var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;
It's just a lot cleaner than:
var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
//whatever you want to do with doubleValue
}
I made a couple extension methods for these cases:
Extension method one
public static bool IsParseableAs<TInput>(this string value) {
var type = typeof(TInput);
var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
new[] { typeof(string), type.MakeByRefType() }, null);
if (tryParseMethod == null) return false;
var arguments = new[] { value, Activator.CreateInstance(type) };
return (bool) tryParseMethod.Invoke(null, arguments);
}
Example:
"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;
Because IsParseableAs() tries to parse the string as the appropriate type instead of just checking if the string is "numeric" it should be pretty safe. And you can even use it for non numeric types that have a TryParse() method, like DateTime.
The method uses reflection and you end up calling the TryParse() method twice which, of course, isn't as efficient, but not everything has to be fully optimized, sometimes convenience is just more important.
This method can also be used to easily parse a list of numeric strings into a list of double or some other type with a default value without having to catch any exceptions:
var sNumbers = new[] {"10", "20", "30"};
var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);
Extension method two
public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
var type = typeof(TOutput);
var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
new[] { typeof(string), type.MakeByRefType() }, null);
if (tryParseMethod == null) return defaultValue;
var arguments = new object[] { value, null };
return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
}
This extension method lets you parse a string as any type that has a TryParse() method and it also lets you specify a default value to return if the conversion fails.
This is better than using the ternary operator with the extension method above as it only does the conversion once. It still uses reflection though...
Examples:
"123".ParseAs<int>(10);
"abc".ParseAs<int>(25);
"123,78".ParseAs<double>(10);
"abc".ParseAs<double>(107.4);
"2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
"monday".ParseAs<DateTime>(DateTime.MinValue);
Outputs:
123
25
123,78
107,4
28.10.2014 00:00:00
01.01.0001 00:00:00
If you want to check if a string is a number (I'm assuming it's a string since if it's a number, duh, you know it's one).
Without regex and
using Microsoft's code as much as possible
you could also do:
public static bool IsNumber(this string aNumber)
{
BigInteger temp_big_int;
var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
return is_number;
}
This will take care of the usual nasties:
Minus (-) or Plus (+) in the beginning
contains decimal character BigIntegers won't parse numbers with decimal points. (So: BigInteger.Parse("3.3") will throw an exception, and TryParse for the same will return false)
no funny non-digits
covers cases where the number is bigger than the usual use of Double.TryParse
You'll have to add a reference to System.Numerics and have
using System.Numerics; on top of your class (well, the second is a bonus I guess :)
Double.TryParse
bool Double.TryParse(string s, out double result)
The best flexible solution with .net built-in function called- char.IsDigit. It works with unlimited long numbers. It will only return true if each character is a numeric number. I used it lot of times with no issues and much easily cleaner solution I ever found. I made a example method.Its ready to use. In addition I added validation for null and empty input. So the method is now totally bulletproof
public static bool IsNumeric(string strNumber)
{
if (string.IsNullOrEmpty(strNumber))
{
return false;
}
else
{
int numberOfChar = strNumber.Count();
if (numberOfChar > 0)
{
bool r = strNumber.All(char.IsDigit);
return r;
}
else
{
return false;
}
}
}
Try the regex define below
new Regex(#"^\d{4}").IsMatch("6") // false
new Regex(#"^\d{4}").IsMatch("68ab") // false
new Regex(#"^\d{4}").IsMatch("1111abcdefg")
new Regex(#"^\d+").IsMatch("6") // true (any length but at least one digit)
With c# 7 it you can inline the out variable:
if(int.TryParse(str, out int v))
{
}
Use these extension methods to clearly distinguish between a check if the string is numerical and if the string only contains 0-9 digits
public static class ExtensionMethods
{
/// <summary>
/// Returns true if string could represent a valid number, including decimals and local culture symbols
/// </summary>
public static bool IsNumeric(this string s)
{
decimal d;
return decimal.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out d);
}
/// <summary>
/// Returns true only if string is wholy comprised of numerical digits
/// </summary>
public static bool IsNumbersOnly(this string s)
{
if (s == null || s == string.Empty)
return false;
foreach (char c in s)
{
if (c < '0' || c > '9') // Avoid using .IsDigit or .IsNumeric as they will return true for other characters
return false;
}
return true;
}
}
public static bool IsNumeric(this string input)
{
int n;
if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
{
foreach (var i in input)
{
if (!int.TryParse(i.ToString(), out n))
{
return false;
}
}
return true;
}
return false;
}
Regex rx = new Regex(#"^([1-9]\d*(\.)\d*|0?(\.)\d*[1-9]\d*|[1-9]\d*)$");
string text = "12.0";
var result = rx.IsMatch(text);
Console.WriteLine(result);
To check string is uint, ulong or contains only digits one .(dot) and digits
Sample inputs
123 => True
123.1 => True
0.123 => True
.123 => True
0.2 => True
3452.434.43=> False
2342f43.34 => False
svasad.324 => False
3215.afa => False
Hope this helps
string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);
if isNumber
{
//string is number
}
else
{
//string is not a number
}
Pull in a reference to Visual Basic in your project and use its Information.IsNumeric method such as shown below and be able to capture floats as well as integers unlike the answer above which only catches ints.
// Using Microsoft.VisualBasic;
var txt = "ABCDEFG";
if (Information.IsNumeric(txt))
Console.WriteLine ("Numeric");
IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false
All the Answers are Useful. But while searching for a solution where the Numeric value is 12 digits or more (in my case), then while debugging, I found the following solution useful :
double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);
Th result variable will give you true or false.
Here is the C# method.
Int.TryParse Method (String, Int32)
bool is_number(string str, char delimiter = '.')
{
if(str.Length==0) //Empty
{
return false;
}
bool is_delimetered = false;
foreach (char c in str)
{
if ((c < '0' || c > '9') && (c != delimiter)) //ASCII table check. Not a digit && not delimeter
{
return false;
}
if (c == delimiter)
{
if (is_delimetered) //more than 1 delimiter
{
return false;
}
else //first time delimiter
{
is_delimetered = true;
}
}
}
return true;
}

Categories