Alan2
Alan2

Reputation: 24572

How can I test an object to see if it is an int with a value of 3?

I have C# method:

public class HeaderType1BoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var s = value as int;
        var ret = (s == 3);
        return !ret;
    }

}

What I need to do is to take that object (which will be an integer), check if its value is 3 and if so return true. Otherwise if it's null or not equal to 3 then I want to return false.

But I am having a problem as it says that

Error CS0077: The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type) (CS0077) (Japanese)

Can someone give me advice on how I can do this check?

Upvotes: 2

Views: 256

Answers (5)

Arslan Ali
Arslan Ali

Reputation: 460

try to use following tested code that eliminate your error.

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (System.Convert.ToInt32(value)==3);
    }

Upvotes: 1

Mark Feldman
Mark Feldman

Reputation: 16118

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    return object.Equals(value, 3);
}

Upvotes: 6

Eugene
Eugene

Reputation: 1533

You cannot use "as" for int, because it is value type. You can use nullable type with "as":

var s = value as int?;

Upvotes: 3

Barr J
Barr J

Reputation: 10927

Two ways:

first is the most straight forward:

try
{
  string x = "text or int";
  int num = Convert.ToInt32(x);
  Console.WriteLine("this num is an int: " + num);
}
catch(Exception ex)
{
  Console.WriteLine("this num is not an int");
}

method 2 with GetType() method and typeof() method:

private bool isNumber(object p_Value)
    {
        try
        {
            if (int.Parse(p_Value.ToString()).GetType().Equals(typeof(int)))
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

Upvotes: 1

Azhy
Azhy

Reputation: 706

You have done some wrong things in your code here is the fixed code to what do you want:-

public class HeaderType1BoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var s = 0;
        try{ s = (int)value; }catch(Exception e){ return false; }
        return s != 3;
    }

}

Upvotes: 1

Related Questions