Learning Objectives
After completing this session, you will be able to: Explain Enumeration in C#
Explain Struct in C#
Enumerations
An enum type declaration defines a type name for a related group of symbolic constants. An enum is a special form of value type, which inherits from System.Enum and supplies alternate names for the values of an underlying primitive type. The underlying type must be one of the built-in signed or unsigned integer types (such as Byte, Int32, or UInt64). You can assign a value of the underlying type to an enumeration and vice versa (no cast is required by the runtime). Enums are used for multiple choice scenarios, in which a runtime decision is made from a fixed number of choices that are known at compile-time.
enum Color { Red, Blue, Green }
The use of enums is superior to the use of integer constants because the use of enums makes the code more readable and self-documenting. The self-documenting nature of the code also makes it possible for the development tool to assist with code writing. For example, the use of Color rather than int for a parameter type enables smart code editors like VS.NET to suggest Color values. Also it mandates certain check constraints like in the following sample, the signature of the Fill method makes it clear that the shape can be filled with one of the given colors.
public void Fill(Color myColor) { myColor2 = myColor;
myColor3 = 0; //...
if( myColor == Color.Red) /...
The following are the members of the E-num class. Public Methods:
S.No Name Description
1 CompareTo Compares this instance to a specified object and returns an indication of their relative values.
2 Equals Overloaded. Overridden. Returns a value indicating whether this instance is equal to a specified object. 3 Format Converts the specified value of a specified enumerated
type to its equivalent string representation according to the specified format.
4 GetHashcode Overridden. Returns the hash code for the value of this instance.
5 GetName Retrieves the name of the constant in the specified enumeration that has the specified value.
6 GetNames Retrieves an array of the names of the constants in a specified enumeration.
7 GetType Gets the Type of the current instance. (Inherited from Object.)
8 GetTypeCode Returns the underlying TypeCode for this instance. 9 GetUnderlyingType Returns the underlying type of the specified
enumeration.
10 GetValues Retrieves an array of the values of the constants in a specified enumeration.
11 IsDefined Returns an indication whether a constant with a specified value exists in a specified enumeration. 12 Parse Overloaded. Converts the string representation of the
name or numeric value of one or more enumerated constants to an equivalent enumerated object.
13 ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.)
14 ToObject Overloaded. Returns an instance of the specified enumeration type set to the specified value. 15 ToString Overloaded. Overridden. Converts the value of this
instance to its equivalent string representation.
Protected Methods:
S.No. Name Description
1 Finalize Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
2 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
In this example, an enumeration, Days is declared. Two enumerators are explicitly converted to integer and assigned to integer variables.
// keyword_enum.cs // enum initialization: using System;
public class EnumTest {
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
static void Main() { int x = (int)Days.Sun; int y = (int)Days.Fri; Console.WriteLine("Sun = {0}", x); Console.WriteLine("Fri = {0}", y); } } Structs
A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following example shows a simple struct declaration:
Public struct Book {
Public decimal price; Public string title; Public string author; }
Structs share almost all the same syntax as classes, although structs are more limited than classes:
Struct instance field declarations cannot use initializers, although static fields on structs can be initialized.
A struct not declare a default constructor —a constructor with no parameters — or a destructor.
Copies of structs are created and destroyed automatically by the compiler, so a default constructor and destructor are unnecessary. In effect, the compiler implements the default constructor by assigning all the fields of their default values .Structs cannot inherit from classes or other structs.
Structs are value types — when an object is created from a struct and assigned to a variable, the variable contains the entire value of the struct. When a variable containing a struct is copied, all of the data is copied, and any modification to the new copy does not change the data for the old copy. Because structs do not use references, they do not have identity — there is no way to distinguish between two instances of a value type with the same data. All value types in C# inherently derive from ValueType, which inherits from Object.
Structs have the following properties:
Structs are value types while classes are reference types.
When passing a struct to a method, it is passed by value instead of as a reference. Unlike classes, structs can be instantiated without using a new operator.
Structs can declare constructors, but they must take parameters.
A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.
A struct can implement interfaces.
It is an error to initialize an instance field in a struct.
Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead. Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.
Summary
Enumerations: It is a data type consisting of a set of named values that represent integral constants.
Struct: It contains an ordered group of data objects and is defined using struct keyword.
Test your Understanding
1. Why do you go for Enumeration?
2. State the difference between structs and classes? 3. What is called as a set of named constants? 4. Are structs suitable only for a small data type?