Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to pass only accepted parameter values

Assuming the following method:

int ExtractMedian(int Statistic)
{
    return ExtractionWork;
}

Is it possible to force Statistic to accept only odd numbers like 1, 3, 5 by using ref for example but without checking the value after it is passed?

like image 597
Explisam Avatar asked Feb 08 '26 03:02

Explisam


2 Answers

Is it possible to force Statistic to accept only odd numbers like 1, 3, 5 by using ref for example but without checking the value after it is passed?

No, I don't think so.

I would simply check at the start of the method:

int ExtractMedian(int Statistic)
{
    if(Statistic % 2 == 0)
        throw new ArgumentException("Statistic must be odd");

    return ExtractionWork;
}
like image 174
Mathias R. Jessen Avatar answered Feb 09 '26 16:02

Mathias R. Jessen


No, there is no way to do that.

Code Contracts COULD be used to force this - but they are basically a post processing step in code that then can get used by an analyzer to see an invalid call. They are NOT part of the integral .NET functionality.

like image 43
TomTom Avatar answered Feb 09 '26 17:02

TomTom



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!