Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# params with a required minimum of one value

Is there a more elegant way of ensuring a constructor is always called with at least one value than what I've got here? I have done it this way as I want a compiler error if no values are provided.

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 have 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();
    }
}

Apologies for editing the code before in an attempt to hide what I was trying to do. It's easier to just paste straight from my code editor!

like image 705
Antony Scott Avatar asked Mar 27 '13 10:03

Antony Scott


1 Answers

What 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 compile-time analysis, and a runtime analyzer.

At least you'll get the warning from static analyzer. And you can turn off runtime analysis in Release mode to avoid performance hit.

like image 58
Artem Koshelev Avatar answered Oct 22 '22 10:10

Artem Koshelev