We can convert a value type to a link type in C # or .net

hi we can convert a value type to a link type in C # or .net languages ​​as int is a value type ... so we can convert its link type

+3
source share
5 answers

This is a topic called boxing and unboxing.

int i = 5;
object o = i;
int j = (int)o;

and etc.

+2
source

For what purpose?

object intAsRef = 32;

is an int as a reference type. But this is called boxing ( see here ) and is usually considered something that can be avoided rather than greedy.

On the other hand, if you want to pass a value object by reference, so that you can change its value inside the method, you need to change the signature of the receive and call method:

public void ChangeValueOfInt(ref int input)
{
    input = 4;
}

int a = 2;
ChangeValueOfInt(ref a);
//a now equals 4
+9
source

, :

int myInt = 5;
object obj = myInt;
+2

"" .NET, , Object. .NET Object :

int myint = 0;
object myIntAsRefType = myInt;

You can do this with other reference types too:

Random rnd = new Random();
object rndAsObject = rnd;

Before you can use any of your own methods or properties, you must remove them:

if(myIntAsRefType is int)
int myNewInt = myIntAsRefType as int;

As an alternative:

if(myIntAsRefType is int)
int myNewInt = (int)myIntAsRefType;
+1
source

With boxing and UnBoxing, you can convert any type of value to a reference type. Boxing will allow you to wrap your value type around an object, and UnBoxing will do the opposite.

Boxing

int i = 10;
Object obj = (Object)i;

unpacking

int j=(int)obj;
0
source

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


All Articles