0

I am creating a basic class that has a user settable property that must be of type int. How do I go about checking that the type passed in by the user is actually an integer and throwing an exception if it is of some other type?

class MyClass
{
    private int _amount;

    public int Amount
    {
        get 
        {
            return _amount;
        }
        set 
        {
            Type t = typeof(value);
            if(t == typeof(int)) 
            {
                _amount = value;
            } 
            else 
            {
                throw new ArgumentException("Amount must be an integer", "Amount");
            }
        }
    }
}

The Visual Studio IDE is saying The type or namespace value could not be found. But I am using the type checking as specified in this SO question. I am using type so the check will take place at compile time.

Community
  • 1
  • 1
webworm
  • 10,587
  • 33
  • 120
  • 217
  • The code you're trying to write is quite pointless in this example: since you declared the property type as `int`, `value` is *required* to be an `int`. Since `int` is a `struct`, it can't be some sort of incompatible subtype or null value, it must be a usable `int`. – Tim S. Jul 11 '14 at 16:33

2 Answers2

3

value is a variable, so typeof doesn't make sense on it (as shown in the linked question).

You need:

set {
  Type t = value.GetType();
  if (t == typeof(int)) {
    _amount = value;
  } else {
    throw new ArgumentException("Amount must be an integer", "Amount");
  }
}

Note that this will never fail at compile time, as the setter isn't actually run until execution. I'm not sure what you are trying to prevent here, the type system will perform the correct cast if you pass it a double or float. The whole check should be unnecessary.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • I see your point about being superfluous :). I was hoping to provide a more "specific" error message to the user of the class as it is quite likely they will try to pass in a decimal as opposed to an integer. – webworm Jul 11 '14 at 16:32
  • well, `Decimal` will cast as well... :) I assume you mean a real (non-whole) number. As far as compile time goes, you may be out of luck. I do believe the user has to explicitly perform the cast in some cases though. – BradleyDotNET Jul 11 '14 at 16:40
2

Well Apart from the fact that value would have to be an integer because the property is declared as an integer!

You need to use the .GetType() method on a value. typeof is a compile time operation.

So

Type t = value.GetType();

However this will crash if value is null...

Bob Vale
  • 18,094
  • 1
  • 42
  • 49