Translate

Tuesday, April 30, 2013

C# Enum Tutorial

An Enum is used where a variable needs to be constrained to a fixed set of values.

The problem that Enum is trying to solve

Suppose I have a class as shown below


    public class User
    {
        public string FirstName { getset; }
        public string LastName { getset; }
        public string Privilege { getset; }
 
    }



How do I make sure that the property "Privilege" can have only one of these values

  • NewUser
  • AverageUser
  • SuperUser
  • Admin

One way to do this would be to alter the class User


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication
{
 
 
 
    public class User
    {
        public string _privilege;
        public string FirstName { getset; }
        public string LastName { getset; }
        public string Privilege
        {
            get { return _privilege; }
            set
            {
                _privilege = value;
                if (_privilege != "NewUser" && _privilege != "AverageUser" && _privilege != "SuperUser" && _privilege != "Admin")
                {
                    throw new Exception("Sorry that value for privilege is not acceptable");
                }
 
            }
 
        }
 
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            var myUser = new User();
            myUser.FirstName = "Dilbert";
            myUser.LastName = "DotNet";
            myUser.Privilege = "Admin";
 
        }
    }
}




You can see that if you are trying to set the Privilege property of the user class, you have to always look it up. Also the Privilege being a string, ideally the case should also be considered (which was not done in the set above). Setting Privilege to be an int instead of a string, will take care of case sensitivity problem, but then the problem that they still have to always look up the values before assigning it, remains. It also makes it harder for someone trying to read the code. For example if you read a line of code


myUser.Privilege =1


it would mean nothing until you look up what the meaning of 1 is supposed to be here.

The bottom line is that whether we use string or int for Privilege, either way the code is hard to use and read. 

How Enum makes it better

Now consider this code below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication
{
 
    public enum UserPrivilege
    {
        NewUser = 1,
        AverageUser = 2,
        SuperUser = 3,
        Admin = 4
 
    }
 
 
    public class User
    {
 
        public string FirstName { getset; }
        public string LastName { getset; }
        public UserPrivilege Privilege { getset; }
 
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            var myUser = new User();
            myUser.FirstName = "Dilbert";
            myUser.LastName = "DotNet";
            myUser.Privilege = UserPrivilege.Admin;
 
        }
    }
}

The advantages of doing it this way are

1>The code is easier to read
 For instance
myUser.Privilege = UserPrivilege.Admin;
tells who ever reads the code that the privilege of the user is Admin.

2>The code intellisense aware












So there is no need to look up the possible values for Privileges.

3>Any illegal assignment can be caught at compile time.
If you try something like
myUser.Privilege = UserPrivilege.Hero;
it will be caught at compile time.


Note here that every Enum value has a string and integer value. So

myUser.Privilege.ToString()  gives you "Admin"
and
(int)myUser.Privilege gives you 4.




How to cast a string into an enum?
In the line of code below, I am casting the string "Admin" into an enum value of the type UserPrivilege.
var  foo = (UserPrivilege)Enum.Parse(typeof(UserPrivilege), "Admin");



How to cast an int into an enum?

In the line of code below foo gets set to UserPrivilege.AverageUser

var foo = (UserPrivilege)2;

However note here that casting an int to an enum always succeeds, even if that enum value does not actually exist. For example you could do

var foo=(UserPrivilege)9999;

Although no defined UserPrivilege has a value of 9999, the above line of code will run.

How to check if an enum value is valid?
To check if the enum is valid, do this

var foo=(UserPrivilege)9999;
Enum.IsDefined(typeof (UserPrivilege), foo);//returns false

How to loop thru a list of enums?

foreach (UserPrivilege privilege in Enum.GetValues(typeof(UserPrivilege)))
 {
   Console.WriteLine(privilege);
 }

Sunday, April 21, 2013

Advantages of Linq C#

What is LINQ?

Skip to Advantages

Linq in .net enables developers to write code in a declarative format Consider the code below. Here what I am trying to do is, find all the numbers in the array "nums", where the number is less that 5. Then I want to order those numbers in ascending order. What is shown below is the traditional way of imperative programming.

int[] nums = { 5, 4, 3, 9, 8, 6, 7, 2, 0 };
int[] small=new int[nums.Length];
int y = 0;

int length = nums.Length;

for (int i = 0; i < length; i++)
{               
    if (nums[i] < 5)
    {
        small[y]=nums[i];
        y++;
    }               
}

Array.Resize(ref small, y);

Array.Sort(small);

for (int i = 0; i < small.Length;i++ )
{
    Console.WriteLine(small[i]);
}

The output of the above code would be 0 2 3 4




If I were to write the same code using LINQ which is a declarative style of programming, this is how the code would look like this

int[] nums = { 5, 4, 3, 9, 8, 6, 7, 2, 0 };

var small = from n in nums where n < 5 orderby n select n;

foreach (var x in small)
{
    Console.WriteLine(x);
}


As you can see above, in a declarative style of programming, you don't need to worry about how it gets done (aka the implementation) . You just tell the compiler, this is what you want and the compiler gets it done for you.

Whats explained above is a practical way to look at it. But strictly speaking LINQ is technology where you can define a provider for a datasource, which can then be used to make declarative LINQ statements to query that datasource. For example,  you can create your own provider that takes LINQ queries and converts it into commands for quering amazon through webservices.  That would be called a LINQ to Amazon provider.

These are the advantages of LINQ

  1. Its a declarative style of programming, hence the code is simpler and lesser.
  2. LINQ provides nearly identical syntax for querying many different data sources such as Collections, Objects, SQL Server, RavenDB etc. Hence you don't have to learn a new syntax for querying every different form of a datasource. You can just use LINQ everywhere.(Note LINQ to XML which is significantly different is an exception)
  3. LINQ provides an object oriented view of the data.
  4. Using LINQ you can take data from one datasource and put that data in another form of data source. For instance using LINQ you can take data from a SQL server and write it into XML with very less code. This property is called the transformative property of LINQ.

1 and 2 are the most important advantages of LINQ.

Wednesday, April 10, 2013

Difference between abstract class and interface c#

Abstract Class
Interface


An abstract class can have method implementations.
An interface cannot have method implementations.
An abstract class can have fields.
An interface cannot have fields
A class can implement only one abstract class.
A class can implement multiple interfaces.
An abstract class tells you what you are. For example if a Person class that implements an abstract class mammal, then that means every person is a mammal.
An interface is merely a feature and doesnot define who you are. For example if your class implements interface IPrint, that does not mean your class is a printer. All it says is that your class have a print feature.