Saturday, May 5, 2018

C#: What is enum in C#

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, which is user defined.

An enum type can be an integer (float, int, byte, double etc.). But if you used beside int it has to be cast.

An enum is used to create numeric constants in .NET framework. All the members of enum are of enum type. Their 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};  
Some points about enum
  • Enums are enumerated data type in c#.
  • Enums are not for end-user, they are meant for developers.
  • Enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same.
  • Enumerations (enums) make your code much more readable and understandable.
  • Enum values are fixed. Enum can be displayed as a string and processed as an integer.
  • The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and ulong.
  • Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums.
  • Enums are value types and are created on the stack and not on the heap.
In C#, enum is a value type data type. The enum is used to declare a list of named integer constants. It can be defined using the enum keyword directly inside a namespace, class, or structure. The enum is used to give a name to each constant so that the constant integer can be referred using its name.
Example: enum

enum WeekDays
{
    Monday = 0,
    Tuesday =1,
    Wednesday = 2,
    Thursday = 3,
    Friday = 4,
    Saturday =5,
    Sunday = 6
}

Console.WriteLine(WeekDays.Friday);
Console.WriteLine((int)WeekDays.Friday);

Output:
Friday 
4
By default, the first member of an enum has the value 0 and the value of each successive enum member is increased by 1. For example, in the following enumeration, Monday is 0, Tuesday is 1, Wednesday is 2 and so forth.
Example: enum

enum WeekDays
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

Console.WriteLine((int)WeekDays.Monday);
Console.WriteLine((int)WeekDays.Friday);

Output:

4
An explicit cast is necessary to convert from enum type to an integral type. For example, to get the int value from an enum:
Example: enum

int dayNum = (int)WeekDays.Friday;

Console.WriteLine(dayNum);

Output:
4
A change in the value of the first enum member will automatically assign incremental values to the other members sequentially. For example, changing the value of Monday to 10, will assign 11 to Tuesday, 12 to Wednesday, and so on:
Example: enum

enum WeekDays
{
    Monday = 10,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
Console.WriteLine((int)WeekDays.Monday);
Console.WriteLine((int)WeekDays.Friday);

Output:
10 
14
The enum can includes named constants of numeric data type e.g. byte, sbyte, short, ushort, int, uint, long, or ulong.
enum cannot be used with string type.
Enum is mainly used to make code more readable by giving related constants a meaningful name. It also improves maintainability.

Enum methods:

Enum is an abstract class that includes static helper methods to work with enums.
Enum methodDescription
FormatConverts the specified value of enum type to the specified string format.
GetNameReturns the name of the constant of the specified value of specified enum.
GetNamesReturns an array of string name of all the constant of specified enum.
GetValuesReturns an array of the values of all the constants of specified enum.
object Parse(type, string)Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
bool TryParse(string, out TEnum)Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The return value indicates whether the conversion succeeded.
Example: enum mehtods

enum WeekDays
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

Console.WriteLine(Enum.GetName(typeof(WeekDays), 4));

Console.WriteLine("WeekDays constant names:");

foreach (string str in Enum.GetNames(typeof(WeekDays)))
            Console.WriteLine(str);

Console.WriteLine("Enum.TryParse():");

WeekDays wdEnum;
Enum.TryParse<WeekDays>("1", out wdEnum);
Console.WriteLine(wdEnum);


Output:
Friday 
WeekDays constant names:
Monday 
Tuesday 
Wednesday 
Thursday
Friday
Saturday
Sunday 
Enum.TryParse(): 
Tuesday
Visit MSDN to know more about enum methods.

Points to Remember :

  1. The enum is a set of named constant.
  2. The value of enum constants starts from 0. Enum can have value of any valid numeric type.
  3. String enum is not supported in C#.
  4. Use of enum makes code more readable and manageable.

C# : What is the difference between Interface and Abstract Class

Theoretically their are some differences between Abstract Class and Interface which are listed below:
  • 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 has 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 member or functions are private by default while in interface all are public, we can’t change them manually.
  • In an abstract class we need to use abstract keyword 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 interface can be used as multiple inheritance.
  • An abstract class use constructor while in an interface we don’t have any type of constructor.

C# : What is the difference between a struct and a class in C#

Answer:
Class and struct both are the user defined data type but have some major difference:

Struct
  • The struct is value type in C# and it inherits from System.Value Type.
  • Struct is usually used for smaller amounts of data.
  • Struct can’t be inherited to other type.
  • A structure can't be abstract.
  • No need to create object by new keyword.
  • Do not have permission to create any default constructor.
Class
  • The class is 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 to other class.
  • A class can be abstract type.
  • We can’t use an object of a class with using new keyword.
  • We can create a default constructor.

C#: What is Boxing and Unboxing

Answer: Boxing and Unboxing both are used for type conversion but have some difference:

Boxing:

Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type. When the CLR boxes a value means when CLR is converting a value type to Object Type, it wraps the value inside a System.Object and stores it on the heap area in application domain. 

Example:ASP.NET

Unboxing:

Unboxing is also a process which is used to extract the value type from the object or any implemented interface type. Boxing may be done implicitly, but unboxing have to be explicit by code. 

Example:ASP.NET

The concept of boxing and unboxing underlines the C# unified view of the type system in which a value of any type can be treated as an object.

C# : What is Managed or Unmanaged Code

Managed Code
“The code, which is developed in .NET framework is known as managed code. This code is directly executed by CLR with the help of managed code execution. Any language that is written in .NET Framework is managed code”.

Unmanaged Code

The code, which is developed outside .NET framework is known as unmanaged code.

“Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level functions of the operating system. Background compatibility with the code of VB, ASP and COM are examples of unmanaged code”.

Unmanaged code can be unmanaged source code and unmanaged compile code. Unmanaged code is executed with the help of wrapper classes.

Wrapper classes are of two types:
  • CCW (COM Callable Wrapper).
  • RCW (Runtime Callable Wrapper).

C#: What is an Object

According to MSDN, "a class or struct definition is like a blueprint that specifies what the type can do. An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection. Client code is the code that uses these variables to call the methods and access the public properties of the object. In an object-oriented language such as C#, a typical program consists of multiple objects interacting dynamically".

Objects helps us to access the member of a class or struct either they can be fields, methods or properties, by using the dot. 

C# : What is C#

C# is the best language for writing Microsoft .NET applications. C# provides the rapid application development found in Visual Basic with the power of C++. Its syntax is similar to C++ syntax and meets 100% of the requirements of OOPs like the following:
  • Abstraction
  • Encapsulation
  • Polymorphism
  • Inheritance

Definition 

Microsoft touts its new, object-oriented language, C#, as the best language for writing Microsoft .NET applications. C# provides the rapid application development found in Visual Basic with the power of C++. C# syntax is similar to C++ syntax. Some experts also say that C# is Microsoft's answer to Sun Microsystems' Java and Borland's Delphi. 

Revision of "Hello World" 

Listing 5.1 provides another quick look at the classic "Hello World" application.

Listing 5.1: HelloWorld.cs, Hello World Example 


using
 System;
class
 HelloWorld{
    static void Main()
    {
        Console.WriteLine("Hello, World");
        Console.WriteLine("Press any key to continue");
        Console.ReadLine();
    }
}


You can copy the code in Listing 5.1 into any editor such as Notepad and save the file as HelloWorld.cs. To compile the program, type the following at the command line:

csc HelloWorld.cs 

Then run the program by typing HelloWorld at command line. The program output is shown in Figure 5.1. 

fig5.1.gif

Figure 5.1: Hello World Example Output 

As discussed in Chapters 3 and 4, using the System statement makes the system namespace and its classes available in the program. The class statement followed by the name of the class defines a new class. Every program should have at least one Main method, which is the entry point of the application. 

The System.Console class defines functionality to read from and write to the system console. The Console.WriteLine method writes a string to the console. 

Object Class and Types 

In .NET, the Object class is the root of all types. All types are implicitly derived from this class so they have access to the methods defined in the Object class. These methods are described in the Table 5.1. 
Method
Description
Equals
Compares whether two object instances are equal. Returns true if two objects are equal; otherwise, returns false.
ReferenceEquals
Compares two object instances. Returns true if both are same instances; otherwise, returns false.
GetHashCode
Returns a hash code for the object.
GetType
Returns a Type object, which holds the types of current instance.
ToString
Converts an instance to a string type and returns a String object.

Table 5.1: The Object Class Methods and Their Descriptions 
Type Information 

The GetType method of the Object class returns a Type object. The Type class is useful when you need to know the internal details of a class such as the type of the class, its attributes, methods, properties, globally unique identifier, name, and fullname. Listing 5.2 demonstrates use of the GetType method. 

Listing 5.2: Type Information Example 


        AClass cls1 = new AClass();
        BClass cls2 = new BClass();
        Type type1 = cls1.GetType();
        Type type2 = cls2.GetType();
        Console.WriteLine(type1.BaseType);
        Console.WriteLine(type1.Name);
        Console.WriteLine(type1.FullName);
        Console.WriteLine(type1.Namespace);


You can use many other methods (GetFields, GetEvents, GetInterfaces, etc.) and properties to obtain more information about an object. 

Comparing Two Objects 

The Object class's Equals and ReferenceEquals methods can be used to compare two objects and their instances, respectively. Listing 5.3 shows one such use of the Equals method. 

Listing 5.3: Compare.cs, Compare Two Objects Example 


using
 System;
// Define A Class

public
 class AClass : Object{
    private void AMethod()
    {
        Console.WriteLine("A method");
    }
}

// Define B Class

public
 class BClass : AClass{
    private void BMethod()
    {
        Console.WriteLine("B method");
    }
}

public
 class Test{
    public static void Main()
    {
        AClass cls1 = new AClass();
        BClass cls2 = new BClass();
        string str1 = "Test";
        string str2 = "Test";
        Console.WriteLine(Object.Equals(cls1, cls2));
        Console.WriteLine(Object.Equals(str1, str2));
        Console.WriteLine("Press any key to continue");
        Console.ReadLine();
    }
}


Figure 5.2 shows the result of the program in Listing 5.3.

fig5.2.gif
Figure 5.2: Screen Generated by Listing 5.3. 
You use ReferenceEquals in the same manner, as shown: 


Console
.WriteLine(Object.ReferenceEquals(obj1, obj2));

Convert to a String Type 

The ToString method of the Object class converts a type to a string type. Because converting to a string type is a very common programming practice, Microsoft defined the ToString method in the Object class, thus making it available to each type in the .NET world through inheritance. The example code in Listing 5.4 converts an integer type and a floating-point number type to a string type. 

Listing 5.4: ToString.cs, Convert to String Example 


using
 System;
public
 class FloatTest{
    public static void Main()
    {
        int i = 12;
        float flt = 12.005f;
        Console.WriteLine(i.ToString());
        Console.WriteLine(flt.ToString());
    }
}


fig5.3.gif

Figure 5.3: Screen Generated by Listing 5.4. 

Hash Code 

You don't use a hash code in regular programming practices, but it's useful if you want to use a type in hashing algorithms such as a hash table. A hash table provides a quick lookup, much like a dictionary. Each member of the hash table has a key value and the object can be referenced by using the key. All members of a class have a memory area defined in the hash table of that class. Members with different names can have the same values but different hash code. By using the method GetHashCode, .NET gives you the flexibility to access the hash code of an object directly and work with it. A derived class can override this method. It's not necessary to return the same hash code for two objects referencing the same value.