Concepts

Boxing and Unboxing

  • Both Boxing and Unboxing are used for converting the type.

BoxingUnboxing

The process of converting from value type to reference (object) type is called Boxing.

The process of converting from reference (object) type to value type in called Unboxing.

Boxing is an implicit conversion.

Unboxing is an explicit conversion.

int i = 123;
object obj = i;    // boxing

object obj = 123;
int i = (int)obj;    // unboxing

Covariance and Contravariance

  • Covariance preserves assignment compatibility and contravariance reverses it.

Parse and TryParse

Parse()TryParse()

returns the converted number

returns a boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter

if the string is not in a valid format, Parse() throws an exception. Use exception handling to the catch the FormatException when the parse operation fails

if the string is not in a valid format, TryParse() returns false.

Convert.ToInt32() uses Parse() internally

Stateful and Stateless Methods

Stateful MethodsStateless Methods

Stateful methods are also known as instance methods.

Stateless methods are knowns as static methods.

When calling a stateful method, you need to create an instance of the class and access the method on the object.

When calling a stateless method, you don't need to create a new instance of its class first.

Example:

Random dice = new Random();

In this example, we created the instance of the class(object) so that the method can access the state of the application.

Example:

Console.WriteLine();

In this example, this method performs its function and finishes without impacting the state of the application in any way.

Last updated