What Is Boxing and Unboxing in C#?: Struct
What Is Boxing and Unboxing in C#?: Struct
The process of converting from a value type to a reference type is called boxing. Boxing is an implicit
conversion. Here is an example of boxing in C#.
1. // Boxing
2. int anum = 123;
3. Object obj = anum;
4. Console.WriteLine(anum);
5. Console.WriteLine(obj);
The process of converting from a reference type to a value type is called unboxing. Here is an example of
unboxing in C#.
1. // Unboxing
2. Object obj2 = 123;
3. int anum2 = (int)obj;
4. Console.WriteLine(anum2);
5. Console.WriteLine(obj);
Class and struct are both user-defined data types, but have some major differences:
Struct
Class
The class is a reference type in C# and it inherits from the System.Object Type.
Classes are usually used for large amounts of data.
Classes can be inherited from other classes.
A class can be an abstract type.
We can create a default constructor.
Read the following articles to learn more about structs vs classes, Struct and Class Differences in C#.
Here are some of the common differences between an interface and an abstract class in C#.
A class can implement any number of interfaces but a subclass can at most use only one abstract
class.
An abstract class can have non-abstract methods (concrete methods) while in case of interface,
all the methods have to be abstract.
An abstract class can declare or use any variables while an interface is not allowed to do so.
In an abstract class, all data members or functions are private by default while in an interface all
are public, we can’t change them manually.
In an abstract class, we need to use abstract keywords to declare abstract methods, while in an
interface we don’t need to use that.
An abstract class can’t be used for multiple inheritance while the interface can be used as
multiple inheritance.
An abstract class use constructor while in an interface we don’t have any type of constructor.
To learn more about the difference between an abstract class and an interface, visit Abstract Class vs
Interface.
An enum is a value type with a set of related named constants often referred to as an enumerator list.
The enum keyword is used to declare an enumeration. It is a primitive data type that is user-defined.
An enum type can be an integer (float, int, byte, double, etc.). But if you use it beside int it has to be
cast.
An enum is used to create numeric constants in the .NET framework. All the members of enum are
enum type. There must be a numeric value for each enum type.
The default underlying type of the enumeration element is int. By default, the first enumerator has the
value 0, and the value of each successive enumerator is increased by 1.
1. enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};