If String Is Empty Then Return Some Default Value

Java - Check Not Null/Empty else assign default value

If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)

If string is empty then return some default value

ActiveSupport adds a presence method to all objects that returns its receiver if present? (the opposite of blank?), and nil otherwise.

Example:

host = config[:host].presence || 'localhost'

How to check id String is Empty then put a define a default value if is Empty in android studio

This assumes that if the String is empty, 0 is passed as default blank value. Also assumes the String will never be null.

(...)
rotation(Float.parseFloat(driver.getBearing().trim().isEmpty()?"0":driver.getBearing()))
(...)

parseFloat will automatically trim() the String. But in order to really check if isEmpty is not giving false negatives, trimming the String guarantees no String with just whitespaces is passed as valid. String s = " "; will return false if called isEmpty() directly on it, without the trim() operation first.

So, the condition driver.getBearing().trim().isEmpty()?"0":driver.getBearing() is telling:

  • If the String is empty, pass "0" (or your desired default value).
  • If not, pass the String value as it is (driver.getBearing()).

Show some default text if return value is null or empty

var article = _newsList.Where(e => e.Id == (item.nValue==""?Guid.Parse(item.nValue):"OLD RECORD"))
.Select(e => e.NewsName).FirstOrDefault();

C#: How to set default value if input is empty

So you want to get the default value of a method-parameter at runtime without repeating yourself, so without typing that value again(f.e. to prevent that have you change it there too if you change the default value of the parameter)?

That's not easy because there is no defaultof(parameter)-operator (similar to the nameof-operator). You had to use reflection.

You could use this extension:

public static class MethodExtensions
{
public static Result<T> ParameterDefault<T>(this MethodBase m, string paramName)
{
ParameterInfo parameter = m.GetParameters()
.FirstOrDefault(p => p.Name == paramName);
if (parameter == null)
throw new ArgumentException($"No parameter with given name '{paramName}' found", nameof(paramName));
if (parameter.ParameterType != typeof(T))
throw new ArgumentException($"Parametertype is not '{typeof(T)}' but '{parameter.ParameterType}'");

if(parameter.HasDefaultValue)
return new Result<T>((T)parameter.DefaultValue, true);
else
return new Result<T>(default(T), false);
}
}

which returns an instance of following class, which is just a wrapper to enable to also return the information if the default value could be determined:

public class Result<T>
{
public Result(T value, bool success)
{
Value = value;
Success = success;
}
public T Value { get; private set; }
public bool Success { get; private set; }
}

Now your method looks like:

public void AddSomething(string ice = "10", string sweet = "20")
{
MethodBase m = MethodBase.GetCurrentMethod();
if (ice == "")
ice = m.ParameterDefault<string>(nameof(ice)).Value;
if (sweet == "")
sweet = m.ParameterDefault<string>(nameof(sweet)).Value;
Console.Write(ice);
Console.Write(sweet);
}

and you don't need to repeat the parameter value.

Why is the default value of the string type null instead of an empty string?

Why is the default value of the string type null instead of an empty
string?

Because string is a reference type and the default value for all reference types is null.

It's quite annoying to test all my strings for null before I can
safely apply methods like ToUpper(), StartWith() etc...

That is consistent with the behaviour of reference types. Before invoking their instance members, one should put a check in place for a null reference.

If the default value of string were the empty string, I would not have
to test, and I would feel it to be more consistent with the other
value types like int or double for example.

Assigning the default value to a specific reference type other than null would make it inconsistent.

Additionally Nullable<String> would make sense.

Nullable<T> works with the value types. Of note is the fact that Nullable was not introduced on the original .NET platform so there would have been a lot of broken code had they changed that rule.(Courtesy @jcolebrand)

Insert variable value or default value if empty in a string

See Bash Default Values

→ echo "my variable contains ${MY_VAR:-default}"
my variable contains default

How to set default value to a string in PHP if another string is empty?

You can use the ternary operator ?:.

If you have PHP 5.3, this is very elegant:

$someString = $someEmptyString ?: 'new text value';

Before 5.3, it needs to be a bit more verbose:

$someString = $someEmptyString ? $someEmptyString : 'new text value';


Related Topics



Leave a reply



Submit