Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple variables in propertys

Tags:

c#

asp.net

I want to return multiple variables in a property

public class Cars
{
    public object value { get; set; }
    public bool worked { get; set; }
}

public Cars GetCar(object value, Cars c)
{
   c.value = value;
   return c;
}

public void Main(string[] args)
{
   Cars c = new Cars();
   string mycar = "ABC-12";
   int mycar2 = 123;

   if (GetCar(mycar, c).value == "ABC") // working
       GetCar(mycar, c).worked = false;

   if (GetCar(mycar, c).value == 1) // error
       GetCar(mycar, c).worked = false;
}

So that if the object is a string that works but if I use that int I get that exception

The == operator can not be applied to "object" and "int" operands

Note: I don't want use Convert.to every time

like image 357
schoko Bong Avatar asked Jan 27 '26 01:01

schoko Bong


2 Answers

You could use the object.Equals method, this will cast both operands to object first:

        if (object.Equals(GetCar(mycar, c).value,"ABC")) // working
            GetCar(mycar, c).worked = false;

        if (object.Equals(GetCar(mycar2, c).value,1)) // compiles, and does not throw exception
            GetCar(mycar2, c).worked = false;
like image 181
GvS Avatar answered Jan 29 '26 18:01

GvS


mycar is of type object. When you set string mycar = "ABC-12", you explicitly set it to be of type string. So once you compare it with an int value you get an exception.

This should also help: if (<object> == <int>)

like image 45
apomene Avatar answered Jan 29 '26 17:01

apomene



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!