Casting, unpacking, conversion ..?

I have been studying value types recently, and I'm a bit confused. Both listing and unboxing use the same syntax - (expected type) (object), right? What about a simple conversion between types, i.e. casting or just conversion?

int x = (int)2.5; //casting?

object a=x;
int Y=(int)a;  //unboxing I think

Random r=new Random();
object X=r;
Random R=(Random)X;  // casting
+3
source share
5 answers

Here you need to consider a lot of things, but first we will take up the simplest ones:

What is the syntax (type)expression?

Well, in its main form casting is considered. You apply an expression from one type to another. What is it.

However, what exactly is happening depends on the type and many other things.

- , , , . , , , , .

, . , .

, , .

:

int a = (int)byteValue;

, , object , .

:

object o = intValue; // boxing
int i = (int)o;      // unboxing

. , "someValueType" - , IDisposable:

IDisposable disp = (IDisposable)someValueType; // boxed

, - .

-, , , , , .

, (. ).

:

string s = (string)myObjectThatCanBeConvertedToAString;

, , .

:

IDisposable disp = (IDisposable)someDisposableObject;
+8

unboxing , unbox ( ), , .

int myInt = 1;
object x = myInt; // box
int  unbox1 = (int)x;  // successful unbox
int? unbox2 = (int?)x; // successful unbox
long unbox3 = (long)x; // error. Can't unbox int to long
long unbox4 = (long)(int)x; // works. First it unboxes to int, and then converts to long

, , . nullable, null null, .

+2

- , .

.

. , , - , X R .

double to int ( ) ( ).

, , - - . , CLR , , - .

+1

Unboxing . Unboxing ( #).

+1

.

int x = (int)2.5; //casting with conversion

object a=x; //casting with boxing
int Y=(int)a;  //casting with unboxing

Random r=new Random();
object X=r;
Random R=(Random)X;  //casting without unboxing

about casting and conversion, check this question: What is the difference between casting and conversion?

0
source

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


All Articles