justHelloWorld
justHelloWorld

Reputation: 6828

Why can I call a method with an object argument on a non-object variable?

I wrote this code in C#:

public static double method ()
{ 
    return 1.3;
}

public static Boolean methodO(object o)
{ 
    return o.Equals(1.3);
}

public static void Main()
{
    System.Console.WriteLine(methodO(method())); // prints 'true'
}

Why does this compile?

Is this because "everything in C# is an object", and so even if it's a primitive type it's an object too and so it implements the "Equals" method?

Upvotes: 1

Views: 162

Answers (1)

Philip Pittle
Philip Pittle

Reputation: 12295

The reason you can pass a value type (double, int, etc) to a method that is expecting an object is .Net will automatically convert the value type to an object. This process is called boxing and you can read more about it on MSDN: https://msdn.microsoft.com/en-us/library/yz2be5wk.aspx

Another way to think about this, is this code is perfectly valid:

int i = 5;
object o = i; //box i into an object
int y = (int)o;  //unbox o into an int

You should also be aware that there is a performance penalty for doing this.

Upvotes: 3

Related Questions