Explain the custom value types in .NET

ASP.NetServer Side ProgrammingProgramming

Variables of value types directly contain the values. When you assign one value type variable to another, each variable associates with a different storage location in memory. Hence, Changing the value of one value type variable doesn't affect the value in the second variable.

Similarly, when you pass an instance of a value type to a method, the compiler copies the memory associated with the argument to a new location associated with the parameter. Any changes to the parameter won't affect the original value. Since memory is copied for value types, they should be small (typically, less than 16 bytes).

All the C# built-in types, such as int, bool, etc. are value types, except string and object, which are reference types. You can also create your own value types using custom value types. There are two types of custom value types in C#: structs and enums.

Structs

Structs are similar to classes and interfaces in syntax, except they use the keyword struct before the name of the type. Similar to classes, structs can contain fields, properties, methods, and constructors. For example, a struct named Point can be defined as follows.

struct Point{
   public int X { get; set; }
   public int Y { get; set; }
}

A constructor in a struct must initialize all the fields and properties within the struct. This is done to ensure that the value type variable is fully initialized by the constructor. Failure to initialize all the data within the struct causes a compile-time error.

All struct types derive from System.ValueType and are sealed by default. That means you cannot inherit from a struct. Struct types can implement interfaces.

Enums

An enum is a value type that you can declare using a set of named constants. To define an enumeration type, use the enum keyword followed by the names of its members.

enum Protocol{
   TCP,
   IP,
   UDP
}

By default, the values of enum members are integers. The first enum value is given the value 0 and each subsequent entry increases by 1. In addition, you can explicitly set the values to integers of your choice.

enum Protocol{
   TCP = 0,
   IP = 50,
   UDP = 100
}

It's not possible to define methods inside an enumeration type. However, using extension methods, you can still add behavior to enumeration types.

An important characteristic of enums is that it declares a set of possible constant values at runtime and make the code easier to read. For example, you can use enums to replace boolean values as follows.

SetState(true);
// vs.
SetState(DeviceState.On);
raja
Published on 19-May-2021 08:15:02
Advertisements