Are there any implicit converters 'out of the box' with C# .Net?

Viewed 91

As per title, does C# .Net offer any implicit converters or are the only implicit converters available the ones that we developers define?

I thought maybe the following would've been a good use-case, for example:

var myObject = new object(); String myString = myObject;

Or, in fact, most types being assigned to a string.

2 Answers

There are lots of reasons why such automatic conversions are not allowed (information loss for a start).

Generally leads to doing the wrong thing (eg. to easy to call the wrong overload): this goes against the idea of the "pit of success".

As an example of this, if you could freely convert anything to a string then this would always work at compile time and runtime:

int GetIntOrZero(string value) {
  Int32.TryParse(value, out int res);
  return res;
}

var myObj = new MyType(args);
var count = GetIntOrZero(myObj);

A function like GetIntOrZero often exists as a helper when processing input, but it makes no sense to apply it to arbitrary objects.

Well, of course there are some obvious ones:

//object
//any_type -> object [note: one way]
object o = some_instance_of_a_type;

//numerics...
//int -> double [note: one way]
int i = 75;
double d = i;

//some more? there always are.

Nevertheless, I would like to raise the argument of type safety to plea against the frequently use of implicit out-of-the-box conversions.

Type safety guard you against common/easy-to-make mistakes as @Richard points out in his answer.

Another example; imagine a implicit conversion from int<->double, then what would this result be?

double d = 75.5;
int i = d;
d = i; //what would d be?

Besides that, your example on string is meaningful in that sense that there are lots of overloads that are designed specifically for that task.

For example;

string.Format("{0}", any_object_here);
//or
$"{any_object_here}";

So, I would say, at this moment, by explicitly need to define the conversions, you'll get the best of both.

Related