Is there an operator or built in function to simplyfy this:
myVal = object1.object2.something(a,b).dataColumn.toString()==""?object1.object2.something(a,b).dataColumn.toString():"-";
I know i can do something like:
string str = object1.object2.something(a,b).dataColumn.toString();
myVal =str==""?"-":str;
but I have many objects and I want to avoid it:
string str1 = object1.object2.something(a,b).dataColumn1.toString();
myVal1==""?str1:"-"
string str2 = object1.object2.something(a,b).dataColumn2.toString();
myVal2==""?str2:"-"
:
string strN = object1.object2.something(a,b).dataColumnN.toString();
myValN==""?strN:"-"
I can also create a function:
private string CheckNull(object dataColumn){
return dataColumn == System.DBNull?"-":dataColumn.toString();
}
myVal1 = CheckNull(object1.object2.something1(a,b).dataColumn.toString())
myVal2 = CheckNull(object1.object2.something2(a,b).dataColumn.toString())
myVal3 = CheckNull(object1.object2.something3(a,b).dataColumn.toString())
The easiest way is to use the ?? operator but the problem is that 'dataColumn' is not compatible with ?? because sometimes returns a system.DBNull instead of a null. Look at the immediate window output:
System.DBNull??"-"
'System.DBNull' is a 'type', which is not valid in the given context
null??"-"
"-"
I wonder if there is some (string) function or operator that can return "-" if dataColumn.toString()=="" without an if..then (because I would have to make many if..then for all of them. Otherwise I rather use the function approach shown above.
string str = object1.object2.something(a,b).dataColumn.toString().if("","-");
How about:
public static class StringHelper {
public static string ValueOrDash(this string value) {
return string.IsNullOrEmpty(value) ? "-" : value;
}
}
Then you can just do:
myVal = object1.object2.something(a,b).DataColumn.ToString().ValueOrDash();
Or better yet:
public static class StringHelper {
public static string ValueOrWhatever(this string value, string defaultValue) {
return string.IsNullOrEmpty(value) ? defaultValue : value;
}
}
myVal = object1.object2.something(a,b).DataColumn.ToString().ValueOrWhatever("-");
If the underlying object is always either a string or DbNull, you could use the as cast operator:
private string CheckNull(object dataColumn){
return dataColumn == (dataColumn as string)??"-":dataColumn;
}
This will also return "-" if the value is an integer for example or some other type.
It's not clear from your code, but if these values are coming from DataRows you could use the new (.NET 3.5) DataRowExtensions.Field function, which will return null instead of DbNull.
You could write an extension method to call on the dataColumn. It wouldn't functionally be much different than your CheckNull method, though.
Or in your first example with str1, str2, strN and such, is there a reason you can't reuse str1 for each? I see you have a method call in your long line of code, you wouldn't want to waste the time running that more often than you need to (especially if it's going to result in the same output every time).
Related
I know how to check when a string is NullOrWhiteSpace. But i want to make my code shorter. And to return a value if my string is null or empty.
Till now i use this:
string Foo=textbox1.Text;
if(string.IsNullOrWhiteSpace(textbox1.Text);
textbox1.Text="UserName";
Is this possible to return this result using one line of code?
string Foo=textbox1.Text ?? "UserName";
In this example it returns me ""; So it thinks that my textbox it is not null, and it doesnt returns me the result i want.
Is there any working example for my case?
textbox1.Text will never be null. If the textbox is empty, it is "", not null. You might use
string Foo = string.IsNullOrWhiteSpace(textbox1.Text) ? "UserName": textbox1.Text;
The null coalescing operator just works with null. Not an empty string.
You could write an extension method to do what you want though.
public static class EX
{
public static string IfNullOrWhiteSpace(this string s, string replacement)
{
if (string.IsNullOrWhiteSpace(s))
{
return replacement;
}
return s;
}
}
Use it like this:
string Foo = textbox1.Text.IfNullOrWhiteSpace("UserName");
Just like the title says.
I've tried doing str.Replace("","0"); but it gave me error because oldValue has zero length.
Is it possible to replace string.Empty into something?
Edit:
I am maintaining a program and I encountered that the program was calling a method that'll return a string then be converted to Int32.
int x = Convert.toInt32(Method1());
public string Method1()
{
string retString = string.Empty;
//Do Something
return retString
}
You can simply return "0" for null, zero length or whitespace string using this one-liner:
return String.IsNullOrWhiteSpace(str) ? "0" : str;
String.Replace takes two string arguments oldValue and newValue. You specified the newValue 0 however an empty string is not legal for the oldValue.
try below code :-
str.Replace(" ","0");
or you can just assign "0" to emptry string as below :-
if(str == string.Empty)
{
str = "0";
}
or making it simple :-
String.IsNullOrWhiteSpace(str) ? "0" : str;
You can't replace empty string within the string, but you can replace, say, spaces, e.g.
str = str.Replace(" ", "0"); // providing str is not null
Or you can substitute empty string with "0":
if (String.IsNullOrEmpty(str))
str = "0";
When parsing string into int you can do something like that:
int x = String.IsNullOrEmpty(str) ? 0 : Convert.ToInt32(str);
In method() you can do:
return String.IsNullOrEmpty(retString) ? "0" : retString;
If you want to check if the value is empty and then set the value to zero, otherwise use the default value you can use an inline if like so:
return string.IsNullOrWhiteSpace(retString ) ? "0" : retString;
If you know that str is empty then you may use star="a"
If you want to check then write statement in if condition.
After your edit:
To convert an empty string to 0, and parse a non-empty string as an integer, I wouldn't deal with a "0" at all, but combine the two in a single method. For example:
int Parse(string s, int d = 0) {
if (string.IsNullOrEmpty(s))
return d;
return int.Parse(s);
}
Try This...
public string Method1()
{
string retString = string.Empty;
//Do Something
return string.IsNullOrEmpty(retString)?"0":retString;
}
It is not possible to replace string.Empty by "0". It will throw ArgumentException.
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll.
Additional information: String cannot be of zero length.
You can try following code:
if(retString == string.Empty)
{
retString = "0";
}
It sounds like your best option would be int.TryParse, if you encounter a string that can't be set to a valid value, it will set it to the default value for an integer (0) as well as returning a boolean so you can know this has happened.
int myInt;
if(!int.TryParse(myStringVariable, out myInt))
{
//Invalid integer you can put something here if you like but not needed
//myInt has been set to zero
}
//The same code without the if statement, still sets myInt
int.TryParse(myStringVariable, out myInt);
In a lot of places I'm using the == operator to compare the string, now I know this considers casing... Is there anyway I can adjust the culture settings to avoid this or do I have to go to every line of code and change it to
string.Compare(a,b,StringComparison.CurrentCultureIgnoreCase)
How about a string extension method?:
public static class StringExtensions {
public static bool EqualsIC(this string self, string string1) {
return self.Equals(string1, StringComparison.InvariantCultureIgnoreCase);
}
}
Then you can just use
string string1 = "Hello world";
string string2 = "hEllO WOrLD";
bool theymatch = string1.EqualsIC(string2);
// OR (per TimS' comment) - to avoid error if string1 is null
theymatch = StringExtensions.EqualsIC(string1, string2);
As an esoteric alternative, you could use Regex instead of String.Compare:
public static bool EqualsICRX(this string self, string string1) {
return Regex.IsMatch(string1, "^" + self + "$", RegexOptions.IgnoreCase);
}
== on strings never considers the culture, so you have to change it.
String == actually is done based only on codepoints, so strings can differ even when looking the same (e.g. if one has composed characters and the other decomposed). Generally you want a more complex notion of 'equality'.
"é" == "é"
== False
I was wondering if there's a syntax for formatting NULL values in string.Format, such as what Excel uses
For example, using Excel I could specify a format value of {0:#,000.00;-#,000.00,NULL}, which means display the numeric value as number format if positive, number format in parenthesis if negative, or NULL if the value is null
string.Format("${0:#,000.00;(#,000.00);NULL}", someNumericValue);
Edit
I'm looking for formatting NULL/Nothing values for all data types, not just numeric ones.
My example is actually incorrect because I mistakenly thought Excel used the 3rd parameter if the value was NULL, but it's actually used when the value is 0. I'm leaving it in there because it's the closest thing I can think of to what I was hoping to do.
I am hoping to avoid the null coalescing operator because I am writing log records, and the data is not usually a string
It would be much easier to write something like
Log(string.Format("Value1 changes from {0:NULL} to {1:NULL}",
new object[] { oldObject.SomeValue, newObject.SomeValue }));
than to write
var old = (oldObject.SomeValue == null ? "null" : oldObject.SomeValue.ToString());
var new = (newObject.SomeValue == null ? "null" : newObject.SomeValue.ToString());
Log(string.Format("Value1 changes from {0} to {1}",
new object[] { old, new }));
You can define a custom formatter that returns "NULL" if the value is null and otherwise the default formatted string, e.g.:
foreach (var value in new[] { 123456.78m, -123456.78m, 0m, (decimal?)null })
{
string result = string.Format(
new NullFormat(), "${0:#,000.00;(#,000.00);ZERO}", value);
Console.WriteLine(result);
}
Output:
$123.456,78
$(123.456,78)
$ZERO
$NULL
Custom Formatter:
public class NullFormat : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type service)
{
if (service == typeof(ICustomFormatter))
{
return this;
}
else
{
return null;
}
}
public string Format(string format, object arg, IFormatProvider provider)
{
if (arg == null)
{
return "NULL";
}
IFormattable formattable = arg as IFormattable;
if (formattable != null)
{
return formattable.ToString(format, provider);
}
return arg.ToString();
}
}
I don't think there's anything in String.Format that will let you specify a particular format for null strings. A workaround is to use the null-coalescing operator, like this:
const string DefaultValue = "(null)";
string s = null;
string formatted = String.Format("{0}", s ?? DefaultValue);
Is this what you want?
string test;
test ?? "NULL"
It looks like String.Format for .NET acts the same way as Excel, i.e., you can use ; separator for positive, negative, and 0 values, but not NULL: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SectionSeparator.
You will probably just have to handle the null value manually:
if (myval == null)
// handle
else
return String.Format(...);
You could use an extension method:
public static string ToDataString(this string prm)
{
if (prm == null)
{
return "NULL";
}
else
{
return "'" + prm.Replace("'", "''") + "'";
}
}
Then in your code you can do:
string Field1="Val";
string Field2=null;
string s = string.Format("Set Value:{0}, NullValue={1}",Field1.ToDataString(), Field2.ToDataString());
What is needed to make String.IsNullOrEmpty() count whitespace strings as empty?
Eg. I want the following to return true instead of the usual false:
String.IsNullOrEmpty(" ");
Is there a better approach than:
String.IsNullOrEmpty(" ".Trim());
(Note that the original question asked what the return would be normally hence the unsympathetic comments, this has been replaced with a more sensible question).
.NET 4.0 will introduce the method String.IsNullOrWhiteSpace. Until then you'll need to use Trim if you want to deal with white space strings the same way you deal with empty strings.
For code not using .NET 4.0, a helper method to check for null or empty or whitespace strings can be implemented like this:
public static bool IsNullOrWhiteSpace(string value)
{
if (String.IsNullOrEmpty(value))
{
return true;
}
return String.IsNullOrEmpty(value.Trim());
}
The String.IsNullOrEmpty will not perform any trimming and will just check if the string is a null reference or an empty string.
String.IsNullOrEmpty(" ")
...Returns False
String foo = null;
String.IsNullOrEmpty( foo.Trim())
...Throws an exception as foo is Null.
String.IsNullOrEmpty( foo ) || foo.Trim() == String.Empty
...Returns true
Of course, you could implement it as an extension function:
static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
return (String.IsNullOrEmpty(value) || String.IsNullOrEmpty(value.Trim()));
}
}