C # parameter with a required minimum of one value

Is there a more elegant way to provide a constructor that is always called with at least one value than mine here? I did it the way I want a compiler error if no values ​​are specified.

public class MyClass { private readonly List<string> _things = new List<string>(); public string[] Things { get { return _things.ToArray(); } } public MyClass(string thing, params string[] things) { _things.Add(thing); _things.AddRange(things); } } 

EDIT

Based on the comments, I changed the code to this ...

 public class Hypermedia : Attribute { private readonly Rel[] _relations; public IEnumerable<Rel> Relations { get { return _relations; } } public Hypermedia(Rel relation, params Rel[] relations) { var list = new List<Rel> {relation}; list.AddRange(relations); _relations = list.ToArray(); } } 

Sorry for editing the code earlier, trying to hide what I was trying to do. It's easier to just paste right from my code editor!

+7
source share
2 answers

How about code contracts ?

 public MyClass(params string[] things) { Contract.Requires(things != null && things.Any()); _things.AddRange(things); } 

Code contracts include classes for marking your code, a static analyzer for analyzing compilation time, and a runtime analyzer.

At least you will get a warning from the static analyzer. And you can turn off run-time analysis in release mode to avoid performance gains.

+13
source

I believe you are looking for RequiredAttribute (available with .NET 3.5)

See http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.aspx for details.

-3
source

All Articles