Friday 15 January 2016

Boxing and Un-boxing


OOPS- Boxing and Unboxing

Object Oriented Programming is a software development style, quite popular in IT industry. Software makes life easy and it more fun when software development is life based. Yes, object oriented programming is based on objects, which means there is nothing technical we have to think for developing software till the first phase of mapping requirements to objects. Its not where we will be playing with functions all the time. Its the object which we will be defining and constructor. It is totally life like. An object would be anything both tangible and intangible.

Well, Boxing and Unboxing are the concepts in OOps.
People get confused all the time between the two.

Well,

Boxing is when we convert value type into type object.


Everything in c# .net is object which means each and everything is inherited from System.Object class. At any point of time, anything is Object and hence can be filled in it without any problem. Therefore, putting anything into object is easy, for example adding water in water, soil in soil, air in air, air in sealed types etcetera, it is easy because the taker and the material are the same at their root level. Hence, boxing is like putting something into a container, the object is a big container, it can take anything, any type into itself, it even can take its own self into itself.It is at memory level a type which is refernce type whihc means it sues both stack and heap to keep and refer data. On stack it keeps the pointer and in heap it keeps the actual data. Heap is big as compared to Stack. In boxing it might be possible we are forcing the object to leave its behaviors and keep everything on stack as value types does.

Unboxing is when converting type object into value type.


It is the reverse of what is happening in Boxing, here we are extracting the Value type from inside the Object. Well, object is a big container, it has to be carefully extracted from it. It might loose data kept inside it[value type]. Object being a big container and when taking out the small value type from it, we need to perform type casting and this casting is specially known as Unboxing. Taking out something from a big box. It is like making the object behave in its natural fashion. Value type back to value types. Hence, making the things natural as they were.

The old non generic lists in c# has the perform both of these while adding and retrieving the data stored in it. It only supported object type. But with new and modern lists , there is a support to generics.
It can be mapped to a type before addition and retrieval of any data.

Thanks and keep hardworking !!!

Ashumeet Mitter

No comments:

Post a Comment