Thursday, June 2, 2016

Lambda expressions in C#

In today's blog post, I will be discussing lambda expressions in C#. They are pretty useful for writing shorthand methods and were introduced in C# 3.

Lambda Expressions

Lambda expressions are methods that appear in line and do not have a name. Lambda expressions are simply more concise syntax of anonymous methods. At compile time all lambda expressions are converted to anonymous methods. Lambda expressions are denoted using lambda operator " => ". To the left of the operator are method arguments and right side denotes the method definition.


Lambda Expressions in C#



Let's look at an example. Suppose we have a method to find multiples of five like this:

public static List<int> GetMultiplesOfFive(List<int> numbers)
{
       var multiples = new List<int>();
       foreach (var num in numbers)
       {
           if (num % 5 == 0)
           {
                multiples.Add(num);
            }
       }
       return multiples;
 }

And then we simply use this method like this:

var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var multiples = GetMultiplesOfFive(numbers);

Now, that's a lot of work to create a method especially if it's being used only once in the code. Instead of creating doing all that, we can simply use lambda expression like this:

var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var multiples = numbers.Where(x => x % 5 == 0).ToList();

This way we didn't have to create a separate method. As I mentioned this is good for any short operation that we want to accomplish without going through the overhead of creating a separate method. The compiler will do it for us :)

The variable referred inside lambda expression (i.e. "x") is not available outside the lambda expression. Also, we can have lambda expressions with multiple parameters or with no parameter. Most of the times compiler can infer the variable type in use in lambda expression, but if not, we can also provide it explicitly. For example,

(int x) => x % 5 == 0

Conclusion

So we saw how lambda expressions can be useful and help us save some time and extra code. They are more of syntactic sugar for writing methods with short definition that are not used more than once (generally).

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, May 26, 2016

Indexers in C#

In today's blog post, we will understand the indexers in C#. Indexers are a useful and less-known feature of C#.

Indexers in C#

An indexer is a way to overload the indexing operator (just like we access array's elements). By defining an indexer on a class, we can access it's properties using an index. Let's take a look at an example to understand how it's done.




Indexers in C#


Suppose we have a Vector class like this:

public class Vector
{
    public int X { get; set; }
    public int Y { get; set; }

    public int this[int index]
    {
        get
        {
            switch (index)
           {
                 case 0: return X;
                 case 1: return Y;
                 default: throw new IndexOutOfRangeException();
           }
        }

        set
        {
            switch (index)
            {
                case 0: X = value;
                    break;
                case 1: Y = value;
                    break;
                default: throw new IndexOutOfRangeException();
            }
        }

    }

}

So here we defined integer indexer in the class. Please note the syntax how we used the "this" keyword with "int index" parameter. Inside the method definition we have the get and set, so we can get the property as well as set the property using integer index.

We are not just limited to integer index. We can even have string indexer like this:


public int this[string index]
{
     get
     {
        switch (index)
        {
              case "x": return X;
              case "X": return X;
              case "y": return Y;
              case "Y": return Y;
              default: throw new IndexOutOfRangeException();
        }

     }

     set
     {
          switch (index)
          {
              case "x":
              case "X":
                  X = value;
                  break;
              case "y":
              case "Y":
                   Y = value;
                   break;
              default: throw new IndexOutOfRangeException();
          }
     }

Please note the "string index" parameter this time. Inside it we define what to do in case of "x" or "X" and "y" or "Y".
Now, let's take a look at how we can use these integer as well as string indexers:

static void Main(string[] args)
{
      var vector1 = new Vector();
      vector1[0] = 2; // integer indexer
      vector1[1] = 3;

      //string indexer
      Console.WriteLine("Vector 1: X = {0}, Y = {1}",
                   vector1["X"], vector1["Y"]);
      Console.ReadLine();
}

So we saw how they can add to readability of the code. Using indexers, we can access each of the property like we are accessing the array elements.

Conclusion

So we saw how to define integer as well as string indexers on a class. Just because we can define indexers doesn't mean it's always the right solution. If it increases the readability of the code and makes sense then only we should use them. In our example, for Vector class it makes it easy to read the code.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, May 19, 2016

Operator Overloading in C#

In today's post, I will be discussing operator overloading in C# with an example.

Operator Overloading

In general, operators like "+", "-", etc have pre-defined functionalities. They can be used for mathematical operations for add, subtract, etc. Using operator overloading, we can have our own implementations for operations where one or both the operands are of a user defined class or struct type.

Operator Overloading in C#



Many operators can be overloaded and some of the operators cannot be overloaded. And some of the operators can be overloaded only in pairs. Here is the table from MSDN that shows the complete list of operators that can be overloaded.


OperatorsOverloadability
+, -, !, ~, ++, --, true, false
These unary operators can be overloaded.
+, -, *, /, %, &, |, ^, <<, >>
These binary operators can be overloaded.
==, !=, <, >, <=, >=
The comparison operators can be overloaded. However, they can be overloaded only in corresponding pairs.
&&, ||
The conditional logical operators cannot be overloaded, but they are evaluated using & and |, which can be overloaded.
[]
The array indexing operator cannot be overloaded, but you can define indexers.
(T)x
The cast operator cannot be overloaded, but you can define new conversion operators.
+=, -=, *=, /=, %=, &=, |=, ^=, <<=,>>=
Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.
=, ., ?:, ??, ->, =>, f(x), as, checked,unchecked, default, delegate, is, new,sizeof, typeof
These operators cannot be overloaded.

Let's take a look at an example of how operator overloading is done. Suppose, we have a Vector class and we want to overload the "+" operator. In order to overload any operator, we need to use "static" keyword and "operator" keyword like this:

public class Vector
{
    public int X { get; set; }
    public int Y { get; set; }

    public static Vector operator +(Vector A, Vector B)
    {
       return new Vector() 
        { X = A.X + B.X, Y = A.Y + B.Y };
    }

}

So now we can simply use "+" operator to add two vectors. So when we add two vectors, it adds their corresponding X and Y values and returns the new vector.

static void Main(string[] args)

{
       var vector1 = new Vector() { X = 2, Y = 3 };
       var vector2 = new Vector() { X = 4, Y = 5 };
       var vector3 = vector1 + vector2;
       Console.WriteLine("The new vector is: X = {0}, Y = {1}.", 
           vector3.X, vector3.Y);
       Console.ReadLine();
}

The result is: The new vector is: X = 6, Y = 8.

Conclusion

We need to use operator overloading very carefully. It's easy to abuse it which can make the application hard to understand and maintain. If the operator overloading is not necessary to use and might make the code look bad, we should avoid it.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Ref: MSDN

Thursday, May 12, 2016

EventHandler with Generics in C#

In previous post, we saw the basic usage of EventHandler in C# here. In this post, we will see how to use EventHandler with generics in C#.

EventHandler With Generics

The EventHandler<TEventArgs> is a predefined delegate that represents an event handler method for event with data. We can use an object of class derived from EventArgs with such an EventHandler. This is essentially useful when we have an event where we want to use some data.


Event With Generics in C#


If we look at the implementation of EventHandler with generics, this is how it's defined:


public delegate void EventHandler<TEventArgs>(object sender, 
            TEventArgs e);

Suppose, we have a User class where we want to trigger an event whenever the user's name is updated. We want the event arguments to have the old user name and the new user name. On user name update, we want to print the old and new user name.

We will first create a new UserNameUpdatedEventArgs derived from EventArgs class.


public class UserNameUpdatedEventArgs : EventArgs
{
    public string OldUserName { get; set; }
    public string NewUserName { get; set; }
}

Next, here is the User class:

public class User {     public int userId;     public string name;     public User(int id, string username)     {         userId = id;         name = username;     }
    public void UpdateUserName(string username)     {         UserNameUpdatedEventArgs args = new            UserNameUpdatedEventArgs();         args.OldUserName = name;         args.NewUserName = username;         OnUserNameUpdated(args);     //event          name = username;     }
    protected virtual void OnUserNameUpdated(           UserNameUpdatedEventArgs e)     {         EventHandler<UserNameUpdatedEventArgs> handler =                 UserNameUpdated;         if (handler != null)         {             handler(this, e);         }     }
    public event EventHandler<UserNameUpdatedEventArgs>        UserNameUpdated; }

Please note how the event args are set in the UpdateUserName method. We set the old and new user names in the UserNameUpdatedEventArgs object and pass it to the event. 

In order to use it in the main method, we simply create a handler and use it like this:

static void Main(string[] args) {       User user = new User(1, "Abhi");       user.UserNameUpdated += program_UserNameUpdated;       user.UpdateUserName("Abhi Jain");       Console.ReadLine(); }
static void program_UserNameUpdated(object sender,       UserNameUpdatedEventArgs e) {     Console.WriteLine("The user name was updated from           {0} to {1}.", e.OldUserName, e.NewUserName); }

The output looks like this:

The user name was updated from Abhi to Abhi Jain

Conclusion

So we saw how to use EventHandler with generics in this post. This is pretty useful when we need to pass in special data.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, April 21, 2016

Events using EventHandler in C#

In today's post, I will be discussing Events using Event Handler in C#. This is in continuation with the previous week post here.

Events without using Delegates keyword explicitly

Last week we discussed what events are and how to use them in our application. We saw how to use events using delegates here. That post was more to show what's going on behind the scenes. The .NET framework has special guidelines on the delegates that can be used for events. The delegate type should have an object parameter and EventArgs parameter and should return void. So the .NET framework has defined a special delegate type called EventHandler for this purpose.

So the last week's example, if we were using EventHandler, will be as follows:


public class ListWithChangedEvent : ArrayList
{
    public event EventHandler Changed;
    protected virtual void OnChanged(EventArgs e)
    {
            if (Changed != null)
                Changed(this, e);
     }

    public override int Add(object value)
    {
        int i = base.Add(value);
         OnChanged(EventArgs.Empty);
        return i;
    }

    public override void Clear()
    {
        base.Clear();
        OnChanged(EventArgs.Empty);
    }

    public override object this[int index]
    {
        set
        {
            base[index] = value;
            OnChanged(EventArgs.Empty);
        }
    }
}

There is no delegate keyword being used explicitly and we just used EventHandler.

Internally, the EventHandler looks like as follows:

public delegate void EventHandler(object sender, EventArgs e);

So, to use the list we can do it the same way as previous post mentioned above:

static void Main(string[] args)
{
     ListWithChangedEvent list = new ListWithChangedEvent();
     list.Changed += ListChanged;
     list.Add("item 1");
     list.Clear();
     Console.ReadLine();
}

private static void ListChanged(object sender, EventArgs e)
{
     Console.WriteLine("This is called when the event fires without delegate.");
}

The list triggers event anytime the list items are changed.

Conclusion

So we saw a simple example of delegates usage using EventHandler. Using EventHandler helps us follow the .NET framework guidelines and adhere to the standard. It's good to know how the delegates work behind the scenes.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Reference: MSDN

Thursday, April 14, 2016

Events Using Delegates in C#

In today's blog post, I will be discussing a simple example of events in C#. We will be using delegates in this post to explain how events work.

Events

An event is a way to notify clients of the occurrence of something of interest to the clients. Events follow a publish-subscribe model. Any client that wants to listen to an event can subscribe to it and when the event occurs the client is notified.

Events in C#

Events Using Delegates

I discussed delegates some time back here. Let's look at an example of how we can implement events using delegates. Here we have an ArrayList which invokes an event called Changed whenever the contents of the list change.

public delegate void ChangedEventHandler(object sender, EventArgs e);

public class ListWithChangedEvent : ArrayList
{
    public event ChangedEventHandler Changed;
    protected virtual void OnChanged(EventArgs e)
    {
            if (Changed != null)
                Changed(this, e);
     }

    public override int Add(object value)
    {
        int i = base.Add(value);
         OnChanged(EventArgs.Empty);
        return i;
    }

    public override void Clear()
    {
        base.Clear();
        OnChanged(EventArgs.Empty);
    }

    public override object this[int index]
    {
        set
        {
            base[index] = value;
            OnChanged(EventArgs.Empty);
        }
    }
}

The delegate is declared first which decides the method signature which can be assigned to the delegate. Next, we declare the special type of list.
Inside the ListWithChangedEvent, first the event is declared. Next, the event is invoked. Inside the method, we check if Changed is not null to avoid null exception. That's a standard practice to avoid null exception while invoking events. Other than that, standard methods are exposed to interact with the List and change it's contents. Inside each of the method, note that the OnChanged event is fired.

Suppose, we want to output a line whenever the event is fired. So we simply have a method like this:

private static void ListChanged(object sender, EventArgs e)
{
      Console.WriteLine("Event Occurred. List Changed.");
}

And then in the Main method we create the list, add the handler to the Changed event. Then, we call the Add and Clear method on the list.

static void Main(string[] args)
{
       ListWithChangedEvent list = new ListWithChangedEvent();
       list.Changed += new ChangedEventHandler(ListChanged);
       list.Add("item 1");
       list.Clear();
       Console.ReadLine();
}

As a result, the event is fired twice, once each for Add and Clear methods.
So we get the output like this:

Event Occurred. List Changed.
Event Occurred. List Changed.


Conclusion

So we saw how to use events using delegates in this post. Events help us decouple our code so the invoking code doesn't need to know what happens when the event is occurred. The calling code itself (or any other part of the system) can decide what to do when the event is fired.  Next week, I will be discussing how to use events without using delegates explicitly.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Reference: MSDN

Thursday, April 7, 2016

Error & Exception Handling in C#

In today's blog post, I will be discussing error and exception handling in C#. We will also be discussing some new features of C# 6 for ways of exception handling.

Error & Exception Handling in C#

In order to make our application more resilient and robust, exception handling is inevitable. There could be several reasons for unforeseen errors in our application. Some times user might enter some bad data, some times some file may be missing, some times some server might be down, some times there might be division by zero and so on. If we don't have proper exception handling in place then our application might crash which certainly is not a nice user experience.

Try Catch Exception

If we have any potentially dangerous code which might throw exception, we can surround it by try block followed by a catch statement.
Here is a simple example:

try
{
       Console.WriteLine("Please Enter a number");
       var input = Console.ReadLine();
       var i = Convert.ToInt32(input);
       Console.WriteLine(String.Format("You entered number: {0}", i ));
}
catch (Exception e)
{
       Console.WriteLine("Number not valid.");
}
Console.ReadLine();

The code snippet asks user to input a number. If the number is valid then no exception is thrown. If the number is not valid, the code will throw an exception. Since we have a catch statement, we will get the output of number not being valid.

Here we had a generic exception handler which can handle any exception. If we want to have several exception handlers, each for several exception types, we can have those. We need to always have more specific exception type before less specific ones. These exception handlers are executed in order. As soon as the first match is found that catch block is executed.

Try Catch Finally

After the try block is executed, the catch exception block might be executed (if there was an exception), and then finally block is executed, if exists. The finally block is useful when we want to execute a block of code no matter if the exception occurred or not. This is useful if we open a file or database connection or something like that. We can close it as part of the finally block.

try
{
    //open connection
}
catch (Exception e)
{
    //handle exception
}
finally
{
    //close connection
}

Exception Filters

Suppose, we want to handle exception only if some specific condition satisfies. Otherwise, we don't want to handle the exception. Until C# 5, we had to do it this way:

try
{
      //Dangerous Code ;)
}
catch(Exception e)
{
     if(e.Message == "Message")
         //do something
     else
         throw;
}

So here we re-threw the exact same exception. The issue with this is that the stack trace is lost when we re-throw the exception. So we loose the information where the exception originally started.
In C# 6, we have exception filters which look like this:

try
{
      //Dangerous Code ;)
}
catch(Exception e) if(e.Message == "Message")
{
      //do something
}

This approach is much more cleaner and there is no re-throw of the exception, so no losing of stack trace.

Conclusion

Exception Handling is necessary for logging and better user experience. By examining these logs, we can improve the application performance too as exceptions generally slow down the application.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)