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

As in the title, does C # .Net offer any implicit converters or are there only single implicit converters available to those that we define by the developers?

I thought that perhaps the following would be a good use case, for example:

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

Or, in fact, most types are assigned string.

+4
source share
2 answers

There are many reasons why such automatic conversions are not allowed (loss of information to begin with).

As a rule, this leads to the wrong one (for example, it is easy to cause the wrong overload): this contradicts the idea of ​​a “pit of success”.

, - string, :

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

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

, GetIntOrZero, , .

+7

, , :

//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.

, , .

/ , @Richard .

; int<->double, ?

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

, , , .

:

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

, , , , .

+2

Source: https://habr.com/ru/post/1689521/


All Articles