Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 349
Houshang.Karami Avatar asked Sep 22 '26 04:09

Houshang.Karami


2 Answers

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

like image 118
Jon Skeet Avatar answered Sep 24 '26 19:09

Jon Skeet


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 };
like image 29
deerchao Avatar answered Sep 24 '26 18:09

deerchao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!