Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

c# - Function Argument Validation

I have a function similar to the following:

(.NET/C#)

public void DoSomething(string country, int year)
{
   ...
}

I am looking to only accept certain two-character codes from a list of ~100+ countries. Additionally, certain countries are only available during certain years. These key-value pairs come from a separate source in the form of a json.

What is the best way to go about verifying valid function input?

My best guess so far is to deserialise the json at run time into a dictionary, and check the input against that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you can cache the valid values, I would create a Dictionary<string, HashSet<int>> and then validate like so:

Dictionary<string, HashSet<int>> validCountryYears; // maybe a field or static field

if (!validCountryYears.TryGetValue(country, out var validYears))
{
    throw new ArgumentException(String.Format("{0} isn't a valid country.", country), nameof(country));
}

if (!validYears.Contains(year))
{
    throw new ArgumentException(String.Format("{0} isn't valid for the country {1}.", year, country), nameof(year));
}

Try it online

P.S. If you require country to be case insensitive then you can specify a StringComparer to the dictionary constructor (e.g. new Dictionary<string, HashSet<int>>(StringComparer.OrdinalIgnoreCase))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...