can we convert value type to referance type in c# or .net supported language
hi can we convert value type to referance type in c# or .开发者_运维百科net supported language like int is value type ...so can we convert it referance type
For what purpose?
object intAsRef = 32;
is an int as a reference type. But this is called boxing (see here) and is generally considered to be something to avoid rather than craved.
On the other hand, if you want to pass a value object by reference so that you can alter its value inside a method then you need to change the signature of the receiving method and the call:
public void ChangeValueOfInt(ref int input)
{
input = 4;
}
int a = 2;
ChangeValueOfInt(ref a);
//a now equals 4
That is the subject called boxing and unboxing.
int i = 5;
object o = i;
int j = (int)o;
etc.
Any value type can be converted to reference type, for example:
int myInt = 5;
object obj = myInt;
The process is called "boxing" in .NET, it refers to the fact that even value types inherit the reference type Object
. Any type in .NET can be cast to Object
thusly:
int myint = 0;
object myIntAsRefType = myInt;
You can do this with other reference types, as well:
Random rnd = new Random();
object rndAsObject = rnd;
Before you can use any of their own methods or properties, you must un-box them:
if(myIntAsRefType is int)
int myNewInt = myIntAsRefType as int;
Alternatively:
if(myIntAsRefType is int)
int myNewInt = (int)myIntAsRefType;
With the help of Boxing and UnBoxing you can convert any value type to reference type. Boxing would allow you to wrap your value type around Object and UnBoxing does the opposite.
Boxing
int i = 10;
Object obj = (Object)i;
UnBoxing
int j=(int)obj;
精彩评论