C# features part 1: C# 2.0 features

Image

C# features from 2.0 to 5.0 version

GENERICS

“Generics are the most powerful feature of C# 2.0. Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code. In concept, generics are similar to C++ templates, but are drastically different in implementation and capabilities. This article discusses the problem space generics address, how they are implemented, the benefits of the programming model, and unique innovations, such as constrains, generic methods and delegates, and generic inheritance. You will also see how generics are utilized in other areas of the .NET Framework such as reflection, arrays, collections, serialization, and remoting, and how to improve on the basic offering.” by MSDN

Generics are very easy feature to learn and it is inevitably to know. It is very easy to learn the basics of C# language like: iterations, classes, structures, methods, properties,… but you will have to learn other parts of the language if you want to say that you really know C#.

So let’s start with basic examples. The most basic example of generic class is List. I believe that everyone has used List at least once. If no, let’s start with the example.

 List<type> _list = new List<type>();

What we have done here? Nothing special. We have just declared a new List and we named it _list. This is type safe code because it is generic. That’s the basic meaning of generics in C#.
List is one of the many collections in C#/.NET so we have to declare a type of that List. Let’s say it’s a string type. That means that we would insert unkown numbers of string in our List. We are declaring that by <> brackets.

How we can declare our own generic class? This is the basic syntax:

 public class OurClass<T>
 {
 ...
 }
 

Where T is a data type we would use in the future code. Also it is important to know that we can declare more than one argument in the generics.

For more about generics look at MSDN.

ANONYMOUS METHODS

Anonymous methods are used when we want to pass a code block as a delegate parameter. It is also a very simple to learn.
Here is the basic example of anonymous method:

 button1.Click += delegate(Object sender, EventArgs e)
 {
 //code that is activated when button1 is clicked
 }
 

Ofc, there is a way to write a similar code without using delegate keyword (using Lamda Expression) but that is not for this post.
From this example you can write any event handler you want (and that is the part of your code).
Be aware that if you want to use code from the example, you will have to write it inside the main part of the code (main part of the code differs from the templates: WinForms, WPF,…), if you want to avoid errors, because IntelliSense will not recognize your object where you want to join the event of that object.

For more information about Anonymous methods look at MSDN.

NULLABLE TYPES

Nullable types are most easiest feature of C# 2.0 to learn. We know that Int32 type holds the range of integer values that we can assign to it from -2147483648 to 2147483647. But what if we want to declare a new integer (Int32 type in this case) and we want of it to be empty but also we want of it to be initialize. In that case we are using “null” value which is not representing zero value.
It is a good practice to do that, so I recommend you to do that in your code in the future.

For more information about the nullable types look at MSDN.

Delegates

It’s been a long time since I post something here. Today I will teach you the basics of delegates which are important part of C# programming.
Delegates may seem hard to learn, but I will show you that it isn’t.
First I will need to teach you some theoretical background before we start with examples.

  1. A delegate is a reference type, like the other reference types (classes, interfaces etc).
  2. It references to a method rather than an object. This is called encapsulating the method.
  3. Delegates can be referred as classes most commonly used within the .NET Framework to build event-handling mechanisms.
  4. Delegates roughly equate to function pointers, commonly used in Visual C++ and other object-oriented languages.
  5. Unlike function pointers however, delegates are object-oriented, type-safe, and secure.
  6. In addition, where a function pointer contains only a reference to a particular function, a delegate consists of a reference to an object, and references to one or more methods within the object.
  7. Delegates can be bound to a single method or to multiple methods, referred to as multicasting.
  8. The binding mechanism used with delegates is dynamic: a delegate can be bound at run time to any method whose signature matches that of the event handler. With this feature, you can set up or change the bound method depending on a condition and to dynamically attach an event handler to a control.
  9. Delegates are ideally suited for use as events — notifications from one component to “listeners” about changes in that component.
  10. Delegates can be used to define callback methods.
  11. Delegates can be chained together; for example, multiple methods can be called on a single event.
  12. Methods do not have to match the delegate signature exactly. For more information, see Using Variance in Delegates (C# and Visual Basic)

Reference: http://social.technet.microsoft.com/wiki/contents/articles/12785.delegates-en-us.aspx

After you understand EVERYTHING from the theory, you should move to basic example. Don’t worry, as always, I will explain the entire code, so you can understand it.
First, open your Visual Studio (mine is 2012 Ultimate) and open a new WPF project (I am bored with console projects) and name the project with some name.
In case you didn’t work with WPF before refer to this site: WPF MSDN
In this example, we will need one Button control and four TextBox controls. Place them in the Window like this:

 

In the first two textBoxes we will make integer inputs. After the inputs, by clicking a button we will get the results in other two textBoxes. Click on the first TextBox control (upper – left) and it will be marked in the XAML code. Make there a new attribute Name and named it “textBox1” and do that for the others. After that you should do that for the Button but you will named it “button1”. We will use those instances in the code, first of all we will use the instance of the Button so we can make an event handler for it and for second case, we will use instances of the TextBoxes so we can manipulate with their values.

After you made all of those instances, we will need to make a code behind the button1 so our application can functionate.

Code behind the button1:


public delegate int sumReturn(int c);
namespace WpfApplication1
{
   ///
   /// Interaction logic for MainWindow.xaml
   ///
   public partial class MainWindow : Window
   {
     static int num = 10;

     public MainWindow()
     {
        InitializeComponent();
        button1.Click += (sender, e) =>
        {
           if (textBox1.Text != "" && textBox2.Text != "")
           {
               sumReturn _sR1 = new sumReturn(AddNum);
               sumReturn _sR2 = new sumReturn(MultNum);

               _sR1(Convert.ToInt32(textBox1.Text));
               textBox3.Text = Convert.ToString(getNum());

               _sR2(Convert.ToInt32(textBox2.Text));
               textBox4.Text = Convert.ToString(getNum());
           }
        };
     }

     public static int AddNum(int p)
     {
        num += p;
        return num;
     }

     public static int MultNum(int q)
     {
        num *= q;
        return num;
     }

     public static int getNum()
     {
        return num;
     }
   }
}

Now, let’s explain what is that code doing.
First, look at the first line I wrote here. This is declaring a delegate. The syntax for declaring the delegate is:

<code>
delegate [return type] [delegate name] ([argument type] argument name,…)
</code>

Based on what delegates are, we have declared “sumReturn” delegate which will return some integer value based on some integer input.
In the MainWindow (which is the entry point in WPF) we have made an event handler for button1 with lambda expression (I will not talk about lamda expression in this post) which will be triggered after we click a button at the runtime. In that event handler we are checking if textBox1 and textBox2 are empty strings or not. If both are not then we will make a two instances of our delegate “sumReturn” named “_sR1” and “_sR2” and they will have AddNum and MultNum as the parameters (I will explain both of those methods). First we are using the first instance, “_sR1”, to store the value of textBox1, and also it will automatically do some calculations. After it did some calculations, we will display the result in the textBox3 and we will do the same for the “_sR2” instance.

To make those things logical, we need to make AddNum, MultNum and getNum methods.
First, AddNum will be public and static and it will return an integer based on some integer input. There, variable “num” will contains the result of summing two integers “num” and “p” and it will return “num” value. The same is going with MultNum but it will not sum “num” and “q”, it will multiply them and we will return the result.
And getNum method is the key method here, which is the real method which will return some value in our application because it will get the passed result from the AddNum or MultNum. Since we have used both of those methods in our entry point, it will return both values.

How to use dll’s inside C# code

What is DLL?

DLL stands for Dynamic Linked Library. In C# it is used when you want to use some function from C/C++ that is written as unmanaged code.

What is API?

An application programming interface (API) is a protocol intended to be used as an interface by software components to communicate with each other.

Syntax of using dll’s inside C# code:


using System.Runtime.InteropServices;

...

[DllImport(dll_filename)]
public|private] static extern ret_type function([type para, ...]);

What all of this mean? It is very important that you are using System.Runtime.InteropServices reference if you are intending to work with dll’s in your code. Why? Because this reference contain definition for DllImport attribute.

DllImport attribute

DllImport attribute must contain at least name of the dll you are going to use. You can also you next parameters:

  •  assembly display name
  • Version
  • Culture
  • PublicKeyToken
  • CharSet
  • other parameters

For example we will use code from the MSDN:


using System;

using System.Runtime.InteropServices;

class user32API
{
 // Use DllImport to import the Win32 MessageBox function.
 [DllImport("user32.dll", CharSet = CharSet.Unicode)]
 public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

static void Main()
 {
 // Call the MessageBox function using platform invoke.
 MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
 }
}

So we can see that even if we use Console application we can invoke MessageBox control to show up with some text.
That is the basic example of using dll’s inside the C# code. For me most good example is using driver functions so you can do both GUI and background with C# to make your application for some device.

Have you ever wonder if you can use system function from C/C++? I will show you that you can. I almost lost my nerves when I was searching for a specific dll to use system function. Here is the code:

[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern string system(string nesto);
static void Main(string[] args)
{
    string[] names = new string[7] { "Ante", "Antonio", "Ivan", "Ana", "Anica", "Ivo", "Perica" };

    var numQuery =
       from nam in names
       where (nam.StartsWith("Ant") || Regex.Match(nam, "[IVN]").Success)
       select nam;

    foreach(string imena in numQuery)
    {
       Console.WriteLine("{0}", imena);
    }
    try
    {
       system("PAUSE");
    }
    catch(DllNotFoundException e)
    {
       Console.WriteLine(e.Message);
    }
}

Don’t bother with the LINQ and RegEx that I have used in this example. I am just happy that I have found the specific dll (msvcrt.dll) that is important if I want to use system function. This is only for learning purpose. Don’t use system function in your C# code because:

Console.ReadKey();

is a better solution.

Prime numbers generator

One of the most popular algorithms for the begginers is the prime numbers generator. This is clasic and there is a too much way to create algorithm that will generate prime numbers in a range from x to y. 

I will show you just one way that is most interesting to me. 

Image

What I have write here?

Let’s start from the begin.

First I have declared two integers that will hold first number and the last number of the cheksum range. After that I made cheksum for those numbers if they satisfy some rules before app can check if numbers are prime. 

If everything goes right, application will go in for loop that will start with the first number that we made in the input and it will goes till that variable is less or equal to the last number in the input. Now we are declaring ‘z’ counter which is initialized to zero (since we didn’t put anything in that counter yet). After that we need to make the crutial part of the algorithm and that is to calculate the square root of each number in the first for loop. 

Now, the rule says that if we want to check if some number is a prime number we must check if that number can be divided by any number from 2 till his square root. If this statement is true ‘z’ counter will rise by one. 

If ‘z’ counter is equal to zero your code will display that number as a prime number. In any other case it will break from for loop.

That would be all from this algorithm. I hope that you have learned something useful🙂

C# and exception classes

Hello everyone. This is my first post on the blog so I will introduce myself first. My name is Antonio Halužan and I am student and a software developer from Croatia.

In this post I will introduce you to one of the most useful things in the .NET and that is exceptions. Why I have decided to talk about that is because you have to expect to have bugs that will show during run time. If you are testing your app or you are just creating a new one this is the most basic thing that you should know so you can cut your time looking in the code and trying to find out what is wrong. And believe me you can spend hours trying to figure out what is wrong with your code.

You may guess why am I talking about this and not about errors. Errors are provided during compile time so your IDE should show you if you have write some wrong syntax or something else. That kind of message will not be shown during run time because you will never get to the run time if your code is not compiled.

For example your app can throw an exception if you have created calculator app and try to divide some number with zero. Since you can’t divide some number with zero it would be great if your app shows some message to you for that kind of logical mistake.

So let start with that example.

First thing first. You have to know that base class for every exception class is class “Exception” (you can find something about that class here: http://msdn.microsoft.com/en-us/library/system.exception(v=vs.71).aspx). And also you will need to know which exception class you should use for “divide by zero” problem. That class is named “DivideByZeroException” and you can find something about this class at this page http://msdn.microsoft.com/en-us/library/system.dividebyzeroexception.aspx

So you may ask yourself what should you do with that class. Since I am talking only about C# on this blog, I will show you code snippet for DivideByZeroException class in C#. It would be great if you could learn about try-catch statement. We are using that statement when we want to say compiler if some part of code can have some kind of bug. Now you can have a clue what we are going to do next. In the next example we will write a very small code which will use everything that I mentioned (except Exception class).

So, let’s get started.

First open a new project and give that project some name (it doesn’t matter what name). I will use ExcExample as a project name and I will choose Console application template which doesn’t have a GUI. Now here is the code you have to write (this is why I include a picture):

ExcExample

 

So let’s make some overview of the code. I have declared 2 integer variables and I have initialized both of them. Pay attention to the second one. Second one is holding number ‘0’. Now you can see that I have declared try statement because I am not sure that I will get the result that I want. Inside that try statement I have declared a new integer variable (c) that will hold a value of a divide by b and I will try to print the result out in the console. You must know that try statement can’t be alone, so I have included catch statement and decided to use DivideByZeroException class and I have created an instance of that class and named it ‘z’. So if something wrong happens inside try statement, compiler will go to catch statement and show catched exception which is “System.DivideByZeroException: Attempted to divide by zero. at ExcExample.Program.Main(string[] args) in …”. So since you know now that there is a logical bug in your code, you can optimize it to check if dividor iz zero or not.

In the next post I will begin with simple algorithm task.
Thank you for reading.