[英]How to set default values to string if it is null or empty
Is there Better way to check if a string is empty or null using Null Coalescing operator.When I use empty value to a string instead of null the null Coalescing operator failed to get me the desired result. Is there Better way to check if a string is empty or null using Null Coalescing operator.When I use empty value to a string instead of null the null Coalescing operator failed to get me the desired result.
string x = null;
string y = x ?? "Default Value";
Console.WriteLine(y);
Here if I replace x = null
with x=""
this doesnt work.在这里,如果我将x = null
替换为x=""
这不起作用。
If I use String.IsNullOrEmpty
method如果我使用String.IsNullOrEmpty
方法
if(String.IsNullOrEmpty(x)
{
y= "default value"
}
{
y =x
}
My code block is having multiple lines and I want to make it simple.我的代码块有多行,我想让它变得简单。 Can you suggest a better way to keep the code clean and simple.您能否提出一种更好的方法来保持代码简洁明了。 As it is used in many places.因为它在许多地方使用。
You can use the ?
你可以使用?
operator操作员
string x = null;
string y = string.IsNullOrEmpty(x) ? "Default Value" : x;
Console.WriteLine(y);
Given that you say "it is used in many places" then it might be appropriate to write an extension method to help with this:鉴于您说“它在很多地方都使用过”,那么编写一个扩展方法来帮助解决这个问题可能是合适的:
public static class StringExt
{
public static string OrIfEmpty(this string? self, string defaultValue)
{
return !string.IsNullOrEmpty(self) ? self : defaultValue;
}
}
Which you would use like so:你会这样使用:
string? x = null;
string y = x.OrIfEmpty("test");
Console.WriteLine(y); // "test"
You could probably choose a better name for OrIfEmpty()
depending on taste.您可能会根据口味为OrIfEmpty()
选择更好的名称。
However, note that this suffers from the drawback that the default value is always evaluated.但是,请注意,这样做的缺点是始终评估默认值。 If obtaining the default is expensive, then using this extension method will hurt performance because the default will always be evaluated even if it's not used.如果获取默认值代价高昂,那么使用此扩展方法将损害性能,因为即使未使用默认值,也会始终对其进行评估。
To circumvent that issue you'd add an extension method to allow you to pass a Func<string>
instead:为了规避这个问题,你需要添加一个扩展方法来允许你传递一个Func<string>
:
public static string OrIfEmpty(this string? self, Func<string> defaultValue)
{
return !string.IsNullOrEmpty(self) ? self : defaultValue();
}
Then when calling it you'd have to pass a delegate for the default, eg:然后在调用它时,您必须为默认值传递一个委托,例如:
public sealed class Program
{
public static void Main()
{
string? x = null;
string y = x.OrIfEmpty(expensiveDefault);
Console.WriteLine(y);
}
static string expensiveDefault()
{
return "test";
}
}
I'm just posting this for consideration.我只是发布这个以供考虑。 Myself, I would just use Marco's answer.我自己,我只会使用 Marco 的答案。 But if you have a LOT of code that does it, then just maybe...但是如果你有很多代码可以做到这一点,那么也许......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.