Horizontal Nav

Friday 28 June 2013

C# Enum


Enums store special values. They make programs simpler. If you place constants directly where used, your C# program becomes complex. It becomes hard to change. Enums instead keep these magic constants in a distinct type.

Example

In this first example, we see an enum type that indicates the importance of something. An enum type internally contains an enumerator list. We use enums when we want readable code that uses constants. 
An enum type is a distinct value type that declares a set of named constants.
Hejlsberg et al., p. 585
Program that uses enums: C#

using System;
class Program
{
    enum Importance
    {
None,
Trivial,
Regular,
Important,
Critical
    };

    static void Main()
    {
// 1.
Importance value = Importance.Critical;

// 2.
if (value == Importance.Trivial)
{
   Console.WriteLine("Not true");
}
else if (value == Importance.Critical)
{
   Console.WriteLine("True");
}
    }
}

Output
True


We see a new variable with the identifier "value" is of the Importance type. It is initialized to Importance.Critical in part 1. At part 2, the variable is tested against other enum constants.

Tip:Enums can be used with IntelliSense in Visual Studio. Visual Studio will guess the value you are typing.
So:You can simply press tab and select the enum type you want. This is an advantage to using enum types.

Saturday 15 June 2013

Difference Between Parameter and Argument

Parameter
Parameter is a variable in the declaration of function.
int add(int x,int y)
{
return x+y;
}
In this example int x,int y are parameters.
Argument
Argument is the actual value of this variable that gets passed to function.
E.g.
int result;
result=add(1,2);

In this example 1,2 are arguments.