Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct overload selection

Tags:

c#

I have the code

//this runs 
string[] s_items = {"0","0"};
string s_output = string.Format("{0}{1}",s_items);

//this one throws a exception
int[] i_items = {0,0};          
string i_output = string.Format("{0}{1}",i_items);

why does the first one run and the second throw a exception? Why selects

int[] the Format(String, Object) overload

string[] the Format(String, Object[]) overload

like image 598
Toshi Avatar asked Jul 11 '18 07:07

Toshi


People also ask

What should I set my overload relay to?

Some manufacturers have the 125% setting built in, which means you must set the overload protection at the motor's nameplate current. If the 125% value is not built into the relay, you must set it at the motor's nameplate current + 25%.

How do you choose a motor overload?

The overloads are determined using 125% of the FLA, 7A x 1.25 = 8.75A. The maximum allowable size for the overloads is 9.8A. The overloads can be sized at 140% of the FLA if the overloads trip at rated load or will not allow the motor to start, 7A x 1.4 = 9.8A.


2 Answers

A string[] can be converted to an object[] because they're both arrays of reference types. And all references are "equal". This is one of the nasty (array) conversions that is built into the C# language from day 1 and should not have existed but we didn't have generics and proper co/contravariance rules from day 1.

An int[] cannot be converted to an object[] because ints, the things actually contained in the first array, are not references.

like image 177
Damien_The_Unbeliever Avatar answered Sep 20 '22 17:09

Damien_The_Unbeliever


From the msdn documentation,

This is a problem of compiler overload resolution. Because the compiler cannot convert an array of integers to an object array, it treats the integer array as a single argument, so it calls the Format(String, Object) method.

See more here.

like image 25
Fabulous Avatar answered Sep 20 '22 17:09

Fabulous