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
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;
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>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With