简体   繁体   中英

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

If I have a method like this:

public void AddSomething(string ice = "10", string sweet = "20")
{
    Console.Write(ice);
    Console.Write(sweet);
}

so if I input a string, it will write the string. If not, it will write the default string (10,20) .

But I want something like this:

public void AddSomething(string ice = "10", string sweet = "20")
{
    if(ice = "")
        ice = default_vaule;    //which is 10
    if(sweet = "")
        sweet = default_vaule;  //which is 20
    Console.Write(ice);
    Console.Write(sweet);
}

so if user input a empty string "" , I can write the default value to user, so I can do not only this:

AddSomething("5");

Also both of these:

AddSomething("5","");
AddSomething("","5");

Anyone knows how to do that? THX!

you already answered your question. you can cover null cases also.

public void AddSomething(string ice = "10", string sweet = "20")
{
    if(string.IsNullOrEmpty(ice)) ice = "10";
    if(string.IsNullOrEmpty(sweet)) sweet = "20";
    Console.Write(ice);
    Console.Write(sweet);
}

you can use constants if you don't want to write duplicate literals.

// these are constant and can be used as default value for parameters.
const string DefaultSweet = "20";     
const string DefaultIce = "10";

public void AddSomething(string ice = DefaultSweet, string sweet = DefaultIce)
{
    if(string.IsNullOrEmpty(ice)) ice = DefaultIce;
    if(string.IsNullOrEmpty(sweet)) sweet = DefaultSweet;
    Console.Write(ice);
    Console.Write(sweet);
}

side note: string.IsNullOrEmpty(ice) is equivalent to ice == "" || ice == null ice == "" || ice == null

So you want to get the default value of a method-parameter at runtime without repeating yourself, so without typing that value again(fe 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.

This question ( at least for me ) is unclear but from what you've posted I can suggest solution like this :

// default value for "ice"
const string default_ice = "10";
// default value for "sweet"
const string default_sweet = "20";

public void AddSomething(string ice = default_ice, string sweet = default_sweet)
{

    // check if "ice" value is set
    if(string.IsNullOrEmpty(ice))
        ice = default_ice;    // set "ice" value to the default one

    // check if "sweet" value is set
    if(string.IsNullOrEmpty(sweet))
        sweet = default_sweet;  // set "sweet" value to the default one

    Console.Write(ice);
    Console.Write(sweet);
}

You can then also call it like such:

AddSomething(sweet: "1337");
// or
AddSomething("13", "37");

or however you like.

Try this online

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM