C# 0 The Complete Reference



Download 4,07 Mb.
Pdf ko'rish
bet402/1096
Sana23.01.2022
Hajmi4,07 Mb.
#402171
1   ...   398   399   400   401   402   403   404   405   ...   1096
Bog'liq
C-Sharp 3 The Complete Reference Herbert Schildt

Boxing and Unboxing

As explained, all C# types, including the value types, are derived from 



object

. Thus, a 

reference of type 

object

 can be used to refer to any other type, including value types. When 

an

object

 reference refers to a value type, a process known as 



boxing

 occurs. Boxing causes 

the value of a value type to be stored in an object instance. Thus, a value type is “boxed” 

inside an object. This object can then be used like any other object. In all cases, boxing occurs 

automatically. You simply assign a value to an 

object

 reference. C# handles the rest.



Unboxing

 is the process of retrieving a value from a boxed object. This action is performed 

using an explicit cast from the 

object

 reference to its corresponding value type. Attempting 

to unbox an object into a different type will result in a runtime error.

www.freepdf-books.com




308

 

P a r t   I :  



T h e   C #   L a n g u a g e

Here is a simple example that illustrates boxing and unboxing:

// A simple boxing/unboxing example.

using System;

class BoxingDemo {

  static void Main() {

    int x;

    object obj;

    x = 10;

    obj = x; // box x into an object

    int y = (int)obj; // unbox obj into an int

    Console.WriteLine(y);

  }

}

This program displays the value 10. Notice that the value in 



x

 is boxed simply by assigning 

it to 


Download 4,07 Mb.

Do'stlaringiz bilan baham:
1   ...   398   399   400   401   402   403   404   405   ...   1096




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish