Houshang.Karami
Houshang.Karami

Reputation: 179

Dynamic class constructor in c#

I have one class with 2 properties called MinValue, MaxValue , If somebody wants to invoke this class and Instantiate this class ,I need some to have constructor that allow select MinValue Or Max Value Or Both Of them , the MinValue and MaxValue both of them are int, So the constructor doesn't allow me like this:

public class Constructor
{
    public int Min { get; set; }
    public int Max { get; set; }
    public Constructor(int MinValue, int MaxValue)
    {
        this.Min = MinValue;
        this.Max = MaxValue;
    }

    public Constructor(int MaxValue)
    {
        this.Max = MaxValue;
    }

    public Constructor(int MinValue)
    {
        this.Min = MinValue;
    }
}

Now I cannot do that because I cannot overload two constructor, How Can I implement this?

Upvotes: 3

Views: 2082

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502816

I would create two static methods for the two parts where you've got only partial information. For example:

public Constructor(int minValue, int maxValue)
{  
    this.Min = minValue;
    this.Max = maxValue;
}

public static Constructor FromMinimumValue(int minValue)
{
    // Adjust default max value as you wish
    return new Constructor(minValue, int.MaxValue);
}

public static Constructor FromMaximumValue(int maxValue)
{
    // Adjust default min value as you wish
    return new Constructor(int.MinValue, maxValue);
}

(The C# 4 option of using named arguments is good too, but only if you know that all your callers will support named arguments.)

Upvotes: 6

abatishchev
abatishchev

Reputation: 100328

public Constructor(int minValue = 0, int maxValue = 0) // requires C# 4+
{
}

or

struct ValueInfo
{
    public MinValue { get; set; }
    public MaxValue { get; set; }
}

public Constructor(ValueInfo values) // one or another or both values can be specified
{
}

Upvotes: 0

deerchao
deerchao

Reputation: 10544

You can't. However, if you're using C# 4.0, you can do this:

class YourTypeName
{
    public YourTypeName(int MinValue = 1,  int MaxValue = 100)
    {  
        this.Min=MinValue;
        this.Max=MaxValue;
    }
}


var a = new YourTypeName(MinValue: 20);
var b = new YourTypeName(MaxValue: 80);

Or, in C# 3.0 and above, you can do this:

class YourTypeName
{
    public YourTypeName()
    {
    }

    public YourTypeName(int MinValue,  int MaxValue)
    {  
        this.Min=MinValue;
        this.Max=MaxValue;
    }

    public int Min {get;set;}

    public int Max {get;set;}
}

var a = new YourTypeName { Min = 20 };
var b = new YourTypeName { Max = 20 };

Upvotes: 4

Related Questions