Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
65 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.

question from:https://stackoverflow.com/questions/65660493/function-argument-validation

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

1 Reply

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))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...