3

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?

Explisam
  • 749
  • 13
  • 26

4 Answers4

7

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;
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
1

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.

TomTom
  • 61,059
  • 10
  • 88
  • 148
1

You will have to do the odd or even check somewhere, and it is usually better practice making it the responsibility of the function to check its input is valid.

Having said that, if this isn't an option, you could make an Odd class, whose values can only be odd numbers.

public class odd {
  int value;
  int get {return value;}
  void set{//check if odd before setting value;}
}
ToxicTeacakes
  • 1,124
  • 1
  • 10
  • 19
  • if anything, I would suggest an immutable struct containing an int value. – Zohar Peled Apr 10 '16 at 08:37
  • excuse my ignorance, but why immutable? – ToxicTeacakes Apr 10 '16 at 08:38
  • 2
    Here is the [short answer](http://stackoverflow.com/questions/441309/why-are-mutable-structs-evil). For the long answer you might also want to [read this.](http://stackoverflow.com/questions/3751911/why-are-c-sharp-structs-immutable) – Zohar Peled Apr 10 '16 at 08:45
0

you can declare argument as a class that has an implicit conversion from int and check value in the class.

public class OddValue  
{  
    private int _value = 1;  
    public int Value  
    {  
        get  
        {  
            return _value;  
        }  

        set
        {  
            if (value % 2 == 0)  
                throw new ArgumentOutOfRangeException();  
            _value = value;  
        }  
    }  

    public OddValue(int value)  
    {  
        this.Value = value;  
    }  
public static implicit operator OddValue(int value)  
    {  
        return new OddValue(value);  
    }  
}  

public static void test(OddValue value)  
    {  

    }  

test(5);  
mehrdad safa
  • 1,081
  • 9
  • 10