C# Switch with String.IsNullOrEmpty - c#

Is it possible to have a switch in C# which checks if the value is null or empty not "" but String.Empty? I know i can do this:
switch (text)
{
case null:
case "":
break;
}
Is there something better, because I don't want to have a large list of IF statements?
I'mm trying to replace:
if (String.IsNullOrEmpty(text))
blah;
else if (text = "hi")
blah

I would suggest something like the following:
switch(text ?? String.Empty)
{
case "":
break;
case "hi":
break;
}
Is that what you are looking for?

What's wrong with your example switch statement?
switch (text)
{
case null:
case "":
foo();
break;
case "hi":
bar();
break;
}
It works (and for some reason that surprised me - I thought it would complain or crash on the null case) and it's clear.
For that matter, why are you worried about String.Empty? I'm missing something here.

how about
if (string.isNullOrEmpty(text))
{
//blah
}
else
{
switch (text)
{
case "hi":
}
}

From the documentation of String.Empty:
The value of this field is the
zero-length string, "".
I interpret this to mean that there is no difference between "" and String.Empty. Why are you trying to distinguish between them?

An empty string is "", which is equal to String.Empty. The reason that you can put "" in a case statement but not "String.Empty" is that "Empty" is a field of the class "String" and "" is actually a contant value.
Constant values are allowed in cases, String.Empty is a field and could be altered at run time. (In this case it will remain the same, but not all static fields of each class are constant values.)
In the case of 'if', that condition is evaluated at run time and if does not require a constant value.
I hope this explains why.

Something that I just noticed is that you can combine if/else and switch statements! Very useful when needing to check preconditions.
if (string.IsNullOrEmpty(text))
{
//blah
}
else switch (text)
{
case "hi":
Console.WriteLine("How about a nice game of chess?");
break;
default:
break;
}

With new c# features, you can use switch expression syntax
text switch
{
"" or null => "a",
_ => "b"
};

string StrMode;
if (!string.IsNullOrEmpty(StrMode))
{
switch (StrMode.Trim())
{
case "Souse":
{
//Statement Eg:
MesssageBox.Show("Souse");
break;
}
case "Company Agent":
{
//Statement Eg:
MesssageBox.Show("Souse");
break;
}
default:
return;
}
}

Related

if string value is used in case then we not need to convert there format before comparison?

I have used below code in a project and someone ask me to use ToLower() or ToUpper() and I think it is unnecessary.
public somefun(Classabc clsabc, string emptype, string id)
{
switch(emptype)
{
case :"AnyInput":
{
//do
}
break;
case :"StringInput":
{
//do
}
break;
}
}
if(emptype=="AnyInput")
{
///
}
Is the above perfect or we need to use ToLower() or ToUpper() with empType in if()? Is there any issue or programming rule violation with my code? According to me in case (switch) we are using email type as constant for case matching and if emptype value can be used in case matching then there is no need to add extra functions to convert to there case before string matching.
Depends on what you guys are looking for.
If the comparison is case sensitive, you can keep the switch-case comparison like you did in the example you provided.
In case the comparison is insensitive, you can pattern matching (C# 7 and above) and write something like this:
switch (true)
{
case bool b when emptype.Equals("AnyInput", StringComparison.InvariantCultureIgnoreCase):
// do
break;
case bool b when emptype.Equals("StringInput", StringComparison.InvariantCultureIgnoreCase):
// do
break;
default:
break;
}

String.Empty in Switch/case statement generate a compiler error

If String.Empty is as good as "", then how come the compiler throws up with string.Empty in the case statement? Nothing can be more constant than string.Empty in my view. Anyone know? Thanks!
switch (filter)
{
case string.Empty: // Compiler error "A constant value is expected"
break;
case "": // It's Okay.
break;
}
You can try like this instead:
switch(filter ?? String.Empty)
string.Empty is a read-only field whereas "" is a compile time constant. You can also go through a article here on Code Project String.Empty Internals
//The Empty constant holds the empty string value.
//We need to call the String constructor so that the compiler doesn't
//mark this as a literal.
//Marking this as a literal would mean that it doesn't show up as a field
//which we can access from native.
public static readonly String Empty = "";
On a side note:
You will also see this issue when you are providing the default parameter value inside your method(C# 4.0):
void myMethod(string filter = string.Empty){}
The above will result in a compile time error as the default value needs to be a constant.
The reason is: you cannot use readonly values in case: consider the following scenario:
public string MyProperty { get; } // is a read-only property of my class
switch (filter)
{
case MyProperty: // wont compile this since it is read only
break;
// rest of statements in Switch
}
As you said string.Empty is equivalent to "", here I can prove this with the same example of a switch statement:
string filter = string.Empty;
switch (filter)
{
case "": // It's Okay.
break;
//rest of statements in Switch
}
Then the only reason it won't allow string.Empty in case it is read-only, the switch won't allow read-only values in its case.

Is it possible to parse "-1.#IND", etc using Double.Parse method

Trying to use System.Double.Parse(string) method for strings such as "-1.#IND" and "INF" representing special values results in a FormatException.
Is there any built-in .NET framework support to parse these?
No, the only non-numeric values double.Parse recognizes are the string values returned by double.Nan.ToString(), double.PositiveInfinity.ToString(), and double.NegativeInfinity.ToString() (dependent on Culture).
In your case I would just use a switch:
double dblValue;
switch strValue
{
case "-1.#IND":
dblValue = double.Nan;
break;
case "INF":
dblValue = double.Infinity;
break;
//... other casess
default:
dblValue = double.Parse(strValue);
break;
}
NaN and other values are parsed in the specified culture (or neutral, if no culture is specified). You can play with those here if you want.
If you have to parse something more special, then just
public double MyParse(string text)
{
if(text == "blablabla")
return double.NaN;
if(text.Contains("blablabla")) ...
if(text.StartsWith(...
return double.Parse(text);
}

how to check if the character is an integer

I am looking for a function that can check the character if it is a integer and do something is so.
char a = '1';
if (Function(a))
{
do something
}
Use System.Char.IsDigit method
If you want just the pure 0-9 digits, use
if(a>='0' && a<='9')
IsNumeric and IsDigit both return true for some characters outside the 0-9 range:
Difference between Char.IsDigit() and Char.IsNumber() in C#
Integer.TryParse works well.
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
The bool Char.IsDigit(char c); Method should work perfectly for this instance.
char a = '1';
if (Char.IsDigit(a))
{
//do something
}
Try using System.Char.IsDigit method.
Try Char.IsNumber. Documentation and examples can be found here
It may be better to just use a switch statement. Something like:
switch(a)
{
case '1':
//do something.
break;
case '2':
// do something else.
break;
default: // Not an integer
throw new FormatException();
break;
}
This will work as long as you're only looking for characters 0-9. Anything more than that (say "10") would be a string and not a character. If you're trying to just see if some input is an integer and the input is a string, you can do:
try
{
Convert.ToInt32("10")
}
catch (FormatException err)
{
// Not an integer, display some error.
}
I have to check the first to characters of a string and if the third character is numeric and do it with MyString.All(char.IsDigit):
if (cAdresse.Trim().ToUpper().Substring(0, 2) == "FZ" & cAdresse.Trim().ToUpper().Substring(2, 1).All(char.IsDigit))
Simplest answer:
char chr = '1';
char.isDigit(chr)

String Comparison

Scenario
Consider the following code snippet.
string s = "S";
string s1 = "S";
string s2 = string.Empty;
switch (s)
{
case "S":
s1 = "StringComparison";
break;
default:
break;
}
switch (s[0])
{
case'S':
s2 = "StringCOmpare2";
break;
default:
break;
}
the first switch case, results in a stringcomparison within IL.
But the second switch case, does not result in a stringcomparison within IL.
Can anyone justify this?
Because on the second switch you're are not doing a String comparison, you're doing a Char comparison.
The easiest answer is that you're not doing a string comparison in the second block; you're comparing two characters.
However, you're right in that the two code blocks are functionally equivalent. A good optimizing compiler should be able to detect that 's' is a fixed-length string, and rewrite it not to use a full string comparison.
You're accessing the string via its indexer which returns a char and so lets you use the string as if it was an array of chars.
So whar you're doing is a char comparison. Using the apostrophe for the 'S' also tells you that you're using 'S' as a char and not as a string.
Your second switch statement isn't using a string, but a single char. Hence, no string comparison.

Categories