I thought I knew C# : Garbage collection & disposal. Part-II

Okay, we are back in to collect “garbage” properly. If you haven’t the first part of this post you might want to read it here. We are following norms and conventions from the first post here too.

 Starting things from where we left off:

This write up continues after the first one where we ended things with SafeHandle class and IDisposable  interface. I do see how intriguing this is of course. But before that, like a unexpected, miserable commercial break before the actual stuff comes on your TV, let’s go have a look on something called finalization.

What you create, you “might” need to destroy:

If you know a little bit of C++ you’d know that there is a thing called destructor and the name implies it does the exactly opposite of what a constructor does. C++ kind of needs it since it doesn’t really have a proper garbage collection paradigm. But that also raises the question of whether C# has a destructor and if it does what does it do and why do we even have one since we said managed resourced would be collected automatically.

Lets jump onto some code, shall we?

class Cat
{
    ~Cart()
    {
        // cleanup things
    }
}

Wait a minute, now this is getting confusing. I have IDisposable::Dispose() and I have a destructor. Both looks like to have same responsibility. Not exactly. Before we confuse ourselves more, lets dig a bit more in the code. To be honest, C# doesn’t really have a destructor, it’s basically a syntactic sugar and inside c sharp compiler translates this segment as

protected override void Finalize()
{
    try
    {
        // Clean things here
    }
    finally
    {
        base.Finalize();
    }
}

We can pick up to things here. First thing is the destructor essentially translates to a overridden Finalize() method. And it also calls the Finalize() base class in the finally block. So, it’s essentially a recursive finalize(). Wait, we have no clue what is Finalize().

Finalize, who art thou?

Finalize is somebody who is blessed to talk with the garbage collector. If you have already questioning where the topics we discussed in last post comes in help, this is the segment. Lets start getting answers for all our confusions on last segment. First, why Finalize is overridden and where does it gets its signature. Finalize gets its signature from Object class. Okay, understandable. What would be the default implementation then? Well, it doesn’t have a default implementation. You might ask why. A little secret to slip in here, remember the mark step of garbage collector. He marks a type instance for finalization if and only if it has overridden the Finalize() method. It’s your way of telling the garbage collector that you need to do some more work before you can reclaim my memory. Garbage collector would mark this guy and put him in a finalization queue which is essentially a list of objects whose finalization codes must be run before GC can reclaim their memory. So, you are possibly left with one more confusion now. And that is, you understood garbage collector uses this method to finalize things, i.e. doing the necessary cleanup. Now, then why do we need IDisposable where we can just override finalize and be done with it, right?

Dispose, you confusing scum!

Turns out dispose intends to point out a pattern in code that you can use to release unmanaged memory. What I didn’t tell you about garbage collector before is you don’t really know when he would essentially do that, you practically have no clue. That also means if you write an app that uses unmanaged resources like crazy like reading 50-60 files at a time, you are using a lot of scarce resources at the same time. And in the end you are waiting for GC to do his job but that guy has no time table. So, hoarding these resources is not a good idea in the meantime. Since releasing unmanaged resources are developers duty, putting that over a finalize method  and waiting for GC to come and invoke that is a stupid way to go. Moreover, if you send an instance to a finalization queue, it means, GC will essentially do the memory cleanup in the next round, he will only invoke finalize this round. That also means GC has to visit you twice to clear off your unused occupied memory which you kinda need now. And the fact that you might want to release the resources NOW is a pretty good reason itself to not wait for GC to do your dirty work. And, when you actually shut down your application, Mr. GC visits you unconditionally and takes out EVERYONE he finds. I hope the need of Dispose() is getting partially clear to you now. We need a method SomeMethod() that we can call which would clean up the unmanaged resources. If we fail to call that at some point, just to make sure garbage collector can call that we will use that same method inside Finalize() so it is called anyhow. If I have not made a fool out of myself at this point, you have figured out the fact that SomeMethod() is Dispose(). Okay, so we know what we are going to do. Now we need to act on it. We will implement the dispose pattern we have been talking about. The first thing we would do here is we would try to write code that reads a couple of lines from a file. We would try to do it the unmanaged way, then move it to slowly to the managed way and in the process we would see how we can use IDisposable there too.

Doing things the unsafe way:

I stole some code from a very old msdn doc which describes a FileReader class like the following:

using System;
using System.Runtime.InteropServices;
public class FileReader
{
    const uint GENERIC_READ = 0x80000000;
    const uint OPEN_EXISTING = 3;
    IntPtr handle;
[DllImport("kernel32", SetLastError = true)]
    static extern unsafe IntPtr CreateFile(
            string FileName,                    // file name
            uint DesiredAccess,                 // access mode
            uint ShareMode,                     // share mode
            uint SecurityAttributes,            // Security Attributes
            uint CreationDisposition,           // how to create
            uint FlagsAndAttributes,            // file attributes
            int hTemplateFile                   // handle to template file
            );
[DllImport("kernel32", SetLastError = true)]
    static extern unsafe bool ReadFile(
            IntPtr hFile,                       // handle to file
            void* pBuffer,                      // data buffer
            int NumberOfBytesToRead,            // number of bytes to read
            int* pNumberOfBytesRead,            // number of bytes read
            int Overlapped                      // overlapped buffer
            );
[DllImport("kernel32", SetLastError = true)]
    static extern unsafe bool CloseHandle(
            IntPtr hObject   // handle to object
            );
    public bool Open(string FileName)
    {
        // open the existing file for reading
        handle = CreateFile(
                FileName,
                GENERIC_READ,
                0,
                0,
                OPEN_EXISTING,
                0,
                0);
if (handle != IntPtr.Zero)
            return true;
        else
            return false;
    }
    public unsafe int Read(byte[] buffer, int index, int count)
    {
        int n = 0;
        fixed (byte* p = buffer)
        {
            if (!ReadFile(handle, p + index, count, &n, 0))
                return 0;
        }
        return n;
    }
    public bool Close()
    {
        // close file handle
        return CloseHandle(handle);
    }
}

Please remember you need to check your Allow Unsafe Code checkbox in your build properties before you start using this class. Lets have a quick run on the code pasted here. I don’t intend to tell everything in details here because that is not the scope of this article. But we will build up on it, so we need to know a little bit. The DllImport attribute here is essentially something  you would need to use an external dll (thus unmanaged) and map the functions inside it to your own managed class. You can also see that’s why we have used the extern keyword here. The implementations of these methods doesn’t live in your code and thus your garbage collector can’t take responsibility of clean up here. 🙂 The next thing you would notice is the fixed statement. fixed statement essentially link up a managed type to an unsafe one and thus make sure GC doesn’t move the managed type when it collects. So, the managed one stays in one place and points to the unmanaged resource perfectly. So, what are we waiting for? Lets read a file.

static int Main(string[] args)
{
    if (args.Length != 1)
    {
        Console.WriteLine("Usage : ReadFile <FileName>");
        return 1;
    }
    if (!System.IO.File.Exists(args[0]))
    {
        Console.WriteLine("File " + args[0] + " not found.");
        return 1;
    }
    byte[] buffer = new byte[128];
    FileReader fr = new FileReader();
    if (fr.Open(args[0]))
    {
        // Assume that an ASCII file is being read
        ASCIIEncoding Encoding = new ASCIIEncoding();
        int bytesRead;
        do
        {
            bytesRead = fr.Read(buffer, 0, buffer.Length);
            string content = Encoding.GetString(buffer, 0, bytesRead);
            Console.Write("{0}", content);
        }
        while (bytesRead > 0);
        fr.Close();
        return 0;
    }
    else
    {
        Console.WriteLine("Failed to open requested file");
        return 1;
    }
}

So, this is essentially a very basic console app and looks somewhat okay. I have created a byte array of size 128 which I would use as a buffer when I read. FileReader returns 0 when it can’t read anymore. Don’t get confused seeing this.

while (bytesRead > 0)

It’s all nice and dandy to be honest. And it works too. Invoke the application (in this case the name here is  TestFileReading.exe) like the following:

TestFileReading.exe somefile.txt

And it works like a charm. But what I did here is we closed the file after use. What if something happens in the middle, something like the file not being available. Or I throw an exception in the middle. What will happen is the file would not be closed up until my process is not closed. And the GC will not take care of it because it doesn’t have anything in the Finalize() method.

Making it safe:

public class FileReader: IDisposable
{
    const uint GENERIC_READ = 0x80000000;
    const uint OPEN_EXISTING = 3;
    IntPtr handle = IntPtr.Zero;
    [DllImport("kernel32", SetLastError = true)]
    static extern unsafe IntPtr CreateFile(
            string FileName,                 // file name
            uint DesiredAccess,             // access mode
            uint ShareMode,                // share mode
            uint SecurityAttributes,      // Security Attributes
            uint CreationDisposition,    // how to create
            uint FlagsAndAttributes,    // file attributes
            int hTemplateFile          // handle to template file
            );
    [DllImport("kernel32", SetLastError = true)]
    static extern unsafe bool ReadFile(
            IntPtr hFile,                   // handle to file
            void* pBuffer,                 // data buffer
            int NumberOfBytesToRead,      // number of bytes to read
            int* pNumberOfBytesRead,     // number of bytes read
            int Overlapped              // overlapped buffer
            );
    [DllImport("kernel32", SetLastError = true)]
    static extern unsafe bool CloseHandle(
            IntPtr hObject   // handle to object
            );
    public bool Open(string FileName)
    {
        // open the existing file for reading
        handle = CreateFile(
                FileName,
                GENERIC_READ,
                0,
                0,
                OPEN_EXISTING,
                0,
                0);
        if (handle != IntPtr.Zero)
            return true;
        else
            return false;
    }
    public unsafe int Read(byte[] buffer, int index, int count)
    {
        int n = 0;
        fixed (byte* p = buffer)
        {
            if (!ReadFile(handle, p + index, count, &n, 0))
                return 0;
        }
        return n;
    }
    public bool Close()
    {
        // close file handle
        return CloseHandle(handle);
    }
    public void Dispose()
    {
        if (handle != IntPtr.Zero)
            Close();
    }
}

Now, in our way towards making things safe, we implemented IDisposable here. That exposed Dispose() and the first thing I did here is we checked whether the handle is IntPtr.Zero and if it’s not we invoked Close(). Dispose() is written this way because it should be invokable in any possible time and it shouldn’t throw any exception if it is invoked multiple times. But is it the solution we want? Look closely. We wanted to have a Finalize() implementation that will essentially do the same things if somehow Dispose() is not called. Right?

Enter the Dispose(bool) overload. We want the parameter less Dispose() to be used by only the external consumers. We would issue a second Dispose(bool) overload where the boolean parameter indicates whether the method call comes from a Dispose method or from the finalizer. It would be true if it is invoked from the parameter less Dispose() method.

With that in mind our code would eventually be this:

    public class FileReader: IDisposable
    {
        const uint GENERIC_READ = 0x80000000;
        const uint OPEN_EXISTING = 3;
        IntPtr handle = IntPtr.Zero;
        private bool isDisposed;

        SafeHandle safeHandle = new SafeFileHandle(IntPtr.Zero, true);

        [DllImport("kernel32", SetLastError = true)]
        static extern unsafe IntPtr CreateFile(
              string FileName,                  // file name
              uint DesiredAccess,              // access mode
              uint ShareMode,                 // share mode
              uint SecurityAttributes,       // Security Attributes
              uint CreationDisposition,     // how to create
              uint FlagsAndAttributes,     // file attributes
              int hTemplateFile           // handle to template file
              );

        [DllImport("kernel32", SetLastError = true)]
        static extern unsafe bool ReadFile(
             IntPtr hFile,                // handle to file
             void* pBuffer,              // data buffer
             int NumberOfBytesToRead,   // number of bytes to read
             int* pNumberOfBytesRead,  // number of bytes read
             int Overlapped           // overlapped buffer
             );

        [DllImport("kernel32", SetLastError = true)]
        static extern unsafe bool CloseHandle(
              IntPtr hObject   // handle to object
              );

        public bool Open(string FileName)
        {
            // open the existing file for reading
            handle = CreateFile(
                  FileName,
                  GENERIC_READ,
                  0,
                  0,
                  OPEN_EXISTING,
                  0,
                  0);

            if (handle != IntPtr.Zero)
                return true;
            else
                return false;
        }

        public unsafe int Read(byte[] buffer, int index, int count)
        {
            int n = 0;
            fixed (byte* p = buffer)
            {
                if (!ReadFile(handle, p + index, count, &n, 0))
                    return 0;
            }
            return n;
        }

        public bool Close()
        {
            // close file handle
            return CloseHandle(handle);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool isDisposing)
        {
            if (isDisposed)
                return;

            if (isDisposing)
            {
                safeHandle.Dispose();
            }

            if (handle != IntPtr.Zero)
                Close();

            isDisposed = true;
        }
    }

Now if you focus on the changes we made here is introducing the following method:

protected virtual void Dispose(bool isDisposing)

Now, this method envisions what we discussed a moment earlier. You can invoke it multiple times without any issue. There are two prominent block here.

  • The conditional block is supposed to free managed resources (Read invoking Dispose() methods of other IDisposable member/properties inside the class, if we have any.)
  • The non-conditional block frees the unmanaged resources.

You might ask why the conditional block tries to dispose managed resources. The GC takes care of that anyway right? Yes, you’re right. Since garbage collector is going to take care of the managed resources anyway, we are making sure the managed resources are disposed on demand if only someone calls the parameter less Dispose(). 

Are we forgetting something again? Remember, you have unmanaged resources and if somehow the Dispose() is not invoked you still have to make sure this is finalized by the garbage collector. Let’s write up a one line destructor here.

 ~FileReader()
 {
    Dispose(false);
 }

It’s pretty straightforward and it complies with everything we said before. Kudos! We are done with FileReader.

Words of Experience:

Although we are safe already. We indeed forgot one thing. If we invoke Dispose() now it will dispose unmanaged and managed resources both. That also means when the garbage collector will come to collect he will see there is a destructor ergo there is a Finalize() override here. So, he would still put this instance into Finalization Queue. That kind of hurts our purpose. Because we wanted to release memory as soon as possible. If the garbage collector has to come back again, that doesn’t really make much sense. So, we would like to suppress the garbage collector to invoke Finalize() if we know we have disposed it ourselves. And a single line modification to the Dispose() method would allow you to do so.

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

We added the following statement to make sure if we have done disposing ourselves the garbage collector would not invoke Finalize() anymore.

GC.SuppressFinalize(this);

Now, please keep in mind that you shouldn’t write a GC.SupperssFinalize() in a derived class since your dispose method would be overridden and you would follow the same pattern and call base.Dispose(isDisposing) in the following way:

class DerivedReader : FileReader
{
   // Flag: Has Dispose already been called?
   bool disposed = false;

   // Protected implementation of Dispose pattern.
   protected override void Dispose(bool disposing)
   {
      if (disposed)
         return; 

      if (disposing) {
         // Free any other managed objects here.
         //
      }

      // Free any unmanaged objects here.
      //
      disposed = true;

      // Call the base class implementation.
      base.Dispose(disposing);
   }

   ~DerivedClass()
   {
      Dispose(false);
   }
}

It should be fairly clear to now why we are doing it this way. We want disposal to go recursively to base class. So, when we dispose the derived class resources, the base class disposes its own resources too.

To use or not to use a Finalizer:

We are almost done, really, we are. This is a section where Im supposed to tell you why you really shouldn’t use unmanaged resources whenever you need. It’s always a good idea not to write a Finalizer if you really really don’t need it. Currently we need it because you are using a unsafe file handle and we need to close it manually. To keep destructor free and as managed as possible, we should always wrap our handles in SafeHandle class and dispose the SafeHandle as a managed resource. Thus, eliminating the need for cleaning unmanaged resources and the overloaded Finalize() . You will find more about that here.

“Using” it right:

Before you figure out why I quoted the word using here, let’s finally wrap our work up. We have made our FileReader class disposable and we would like to invoke dispose() after we are done using it. We would opt for a try-catch-finally block to do it and will dispose the resources in the finally block.

FileReader fr = new FileReader();
try
{
    if (fr.Open(args[0]))
    {
        // Assume that an ASCII file is being read
        ASCIIEncoding Encoding = new ASCIIEncoding();
        int bytesRead;
        do
        {
            bytesRead = fr.Read(buffer, 0, buffer.Length);
            string content = Encoding.GetString(buffer, 0, bytesRead);
            Console.Write("{0}", content);
        }
        while (bytesRead > 0);
        return 0;
    }
    else
    {
        Console.WriteLine("Failed to open requested file");
        return 1;
    }
}
finally
{
    if (fr != null)
        fr.Dispose();
}

The only difference you see here that we don’t explicitly call Close() anymore. Because that is already handled when we are disposing the FileReader instance.

Good thing for you is that C# has essentially made things even easier than this. Remember the using statements we used in Part-I? An using statement is basically a syntactic sugar placed on a try-finally block with a call to Dispose() in the finally block just like we wrote it here. Now, with that in mind, our code-block will change to:

using (FileReader fr = new FileReader())
{
    if (fr.Open(args[0]))
    {
        // Assume that an ASCII file is being read
        ASCIIEncoding Encoding = new ASCIIEncoding();
        int bytesRead;
        do
        {
            bytesRead = fr.Read(buffer, 0, buffer.Length);
            string content = Encoding.GetString(buffer, 0, bytesRead);
            Console.Write("{0}", content);
        }
        while (bytesRead > 0);
        return 0;
    }
    else
    {
        Console.WriteLine("Failed to open requested file");
        return 1;
    }
}

Now you can go back to part-I and try to understand the first bits of code we saw. I hope it would make a bit better sense to you now. Hope you like it. Hopefully, if there’s a next part, I would talk about garbage collection algorithms.

You can find the code sample over github here.

Different Operators in C#

In this article we will discuss about common operators that used in C#. Like any other programming languages C# has also some common operators. We can divide those as the following –
• Assignment Operator (=)
• Arithmetic Operators (+,-,*,/,%)
• Comparison Operators (==,!=,>,>=,<,<=)
• Conditional Operators (&&,||)
• Ternary Operator (?:)
• Null Coalescing Operator (??)
Now we will discuss about each of this operator in details.

Assignment Operator (=)

This is a very common operator in every programming language. It is used to assign a value in a variable. We can give a variable a value by this operator. Suppose we declare a variable by the following instruction-

Int variable_name;

Then this variable reserve some memory in RAM but no value is saved in those memory. We can assign value to those memory by using assignment operator as follows-

Int variable_name=5;

Now the value 5 is reserved in those memory blocks. So assignment operator is used to assign values.

Arithmetic Operators (+,-,*,/,%)

These operators are used to perform arithmetic operation. In many places of a program we need to perform many arithmetic operation. So it is important to understand these operators closely.
The “+” operator performs addition operation. Suppose we want to add two values. Then we can do that by the following-

Int a = 5+4;
Or,
Int a=5;
Int b=6;
Int result= a+b;

The “+” operator takes two operands and return the result of addition between those operands. Similarly “-” operator performs the subtraction operation between two operands. It will subtract its right side operand from left side operand and return the result. The multiplication operator is “*”. It will perform multiplication operation.
Now the two operator / and % is related to division operation. The forward slash (/) operator returns the quotient of the division operation and “%” (read as MOD) operator returns the reminder. To understand the difference we consider a division operation. Suppose we want to divide 10 by 2. So here the Quotient will be 5 and reminder will be 0. If we use / operator then it will return 5 and if we use % then it will return 0. Consider the following program-

using System;
class Program
{
   static void Main()
    {
        int Numerator = 10;
        int Denominator = 2;

        int result = Numerator / Denominator;

        Console.WriteLine("{0}", result);
    }
}

The above program will print 5 because here we use / operator and it will return quotient. If we used % in place of / then it will print the reminder that is 0 here.

Comparison Operators (==,!=,>,>=,<,<=)

Comparison operators are used to compare to value and always return true or false. Every comparison operator has a meaning and performs a specific compare operation. The best example of this operator is in conditional statement. The statement in which we compare something in respect with some condition is called conditional statement. There are some keywords that used in conditional statement, one of this is “if” keyword. It is very common in almost all programming languages.
The double equal sign is used to compare equality. Consider the following example-

using System;
class Program
{
   static void Main()
    {
        int a = 10;
       if(a==10)
       {
           Console.WriteLine("{0}", a);
       }
        
    }
} 

In the above example we compare the value of variable with 10. If the value of variable a is equal to 10 then the next instruction will execute. The next instruction is to print the value of ‘a’ that is 10 here. So the program will print 10.
The “!=” operator is used to check inequality. For example in the above example we can check the variable ‘a’ is not equal or not. If we want to execute another instruction if the variable is not equal to 10 then code should be as follows-

using System;
class Program
{
   static void Main()
    {
        int a = 5;
       if(a==10)
       {
           Console.WriteLine("{0}", a);
       }
       if(a!=10)
       {
           Console.WriteLine("a is not equal to 10");
       }
    }
}

The above program will print “a is not equal to 10” because the value of a is 5 here. The != operator used here to execute the meaningful string that user can understand specifically that a is not equal to 10.
Similarly we can check greater than relation by the “>” operator. It will return true if the right side operand is greater than the left side operand. If we want to check greater or equal relation then we can use >= operator. It will return true if the left side operand is greater than right side operand and also if the operands are equal to each other.
Like greater than relation we can check less than relation by “<” operator and less than or equal relation by “<=” operator.

Conditional Operators (&&,||)

There are two operators that used in conditional statements named as AND (&&) and OR (||). If there is any situation where we need to execute a statement if and only if some of conditions are true then we can use && operator. This operator takes two condition and execute next instructions if all of those conditions are true. Suppose we have to check if a number is less than 5 and greater than 1 or not then we can check it by && operator as following-

using System;
class Program
{
   static void Main()
    {
        int a=2;
        
       if(a1 )
       {
           Console.WriteLine("a is less than 5 and greater than 1");
       }
        
    }
}

In the above example two conditions is checked, one is a is less than 5 and the other is a is greater than 1. So the print instruction will be executed if each of these instruction are true. Another operator is || (OR) this operator used as the same of && operator but if any one of the condition is true between two then the next instruction will execute. The OR operator return true if any one of the condition is true. In the above example if we used OR operator then weather the value of a is less than 5 or greater than 1 the print instruction will execute.

 
using System;
class Program
{
   static void Main()
    {
        int a=10;
        
       if(a1 )
       {
           Console.WriteLine("a is less than 5 OR greater than 1");
       }
        
    }
}

In the above example the condition a is less than 5 is false but a is greater than 1 true, so one of the condition is true. That’s why the print instruction will execute.

Ternary Operator (?:)

The ternary operator is a very interesting operator. It gives us two options if any condition is true than do something otherwise do something. The syntax of ternary operator can be written as follows-
Any Condition ? do if the condition is true : do if condition is false
We can see it by the following code-

using System;
class Program
{
   static void Main()
    {
        int a=10;
        bool ISValue10 = a == 10 ? true : false;

        Console.WriteLine("{0}", ISValue10);
        
    }
}

In the above example the condition is if the variable “a” is equal to 10 or not. If it is true then the bool type variable “ISValue10” will be assigned by true otherwise false. Here the example will print true because here the value of variable is 10. We can do the same by if statement but it will take more instruction that we have done here with one instruction. That is the benefit of using ternary operator.

Null Coalescing Operator (??)

To understand null coalescing operator first we have to understand nullable types in C#. Actually we can divide the types in C# in two broad categories-
• Value types
• Reference types
In the previous article we have already seen the value types and those are- integer, double, float, decimal etc. We have also seen a reference type that is string type. String is actually a class. We will discuss about reference types and value types in details in the later session. What we need to understand at this point is types in C# can be divided in two broad categories that is value type and reference type. Example of value type is integer, float, double, structs, enums and example of reference type is interface, delegates, arrays, class etc. And another point we need to keep in mind at this point is the default value of a reference type is null and the default value for value type is some form of zero. For example the default value of type integer is zero and it cannot hold the value null. To assign null in a variable we use the keyword null in C#. If we try to assign null to a integer type variable then we will get an error. So value type cannot hold null value. But as I told before that string is a class that is reference type so we can assign a string variable with null. For an example we can write-

 
string s = null;

but we cannot write-

int a = null; 

If we try to assign null to a integer type variable then it will return an immediate error. Sometimes it is necessary to assign a value types variable with the value null. Generally it is necessary if we use C# to communicate with a database. Since nullable types and non-nullable types is not a concept of database it is a concept of C#, any of the field in a database can be null. Sometimes for making decision it is necessary to assign null to value type variable. Again we get here two types, one is nullable and the other is non-nullable. We can assign null to non-nullable types by using the ? operator.
Suppose we have a form that ask the user a question “Are you a teacher?” and this field is optional. User can say yes or no and the user can also keep the field empty. If we have a bool type variable to store the answer then we can assign true or false in this variable nothing else. But if the user keep the field empty we need to assign null to bool type variable. We can do it by using ? operator as follows.

bool? ISUserTeacher = null;

So we can make a non-nullable type a nullable type by using ? operator. Now consider an example to understand null coalescing operator. Suppose a have 10 mangoes in a tree and we store the result in a integer type variable as follows-

int MangoesInTree = 10; 

Now it is possible that there is no mangoes in the tree. So we have to make the integer variable a nullable variable that we can assign null value to it. We can do it as follows-

int? MangoesInTree = null; 

Suppose we have another variable named availablemangoes and we will assign the value of MangoesInTree in it if MangoesInTree is not null. If MangoesInTree is null then we will assign 0 to availablemangoes variable. We can do it as follows-

using System;
class Program
{
   static void Main()
    {
        int? MangoesInTree = null;

        int availablemangoes;

       if(MangoesInTree==null)
       {
           availablemangoes = 0;
       }
       else
       {
           availablemangoes = MangoesInTree;
       }
	Console.WriteLine(“{0}”,availablemangoes);
    }
}

Unfortunately we will get an error here that “cannot imlicitly convert type int? to int”. Here MangoesInTree variable is a nullable variable but availablemangoes is not a nullable variable so it cannot be assigned by the nullable types. Here we can use a way to do it. It is called type casting. We will discuss about type casting and implicit, explicit type conversion in the very next article. So just for now note it, we can do the above program as follows-

using System;
class Program
{
   static void Main()
    {
        int? MangoesInTree = null;

        int availablemangoes;

       if(MangoesInTree==null)
       {
           availablemangoes = 0;
       }
       else
       {
           availablemangoes = (int)MangoesInTree;
       }
Console.WriteLine(“{0}”,availablemangoes);

    }
} 

Now it will print the value of availablemangoes as we wanted. But we can do the same program with just one line and this is what the null coalescing operator is. We can do the same program with null coalescing operator. The above program with null coalescing operator can be written as follows-

using System;
class Program
{
   static void Main()
    {
        int? MangoesInTree = 10;

        int availablemangoes;

        availablemangoes = MangoesInTree ?? 0;

       Console.WriteLine("{0}", availablemangoes);
    }
}

Look closely to the above program here we do the same thing with just one line of code. Here the default value what we want to assign in non-nullable variable is given after the null coalescing operator (??) and before the operator we supply the value that we want to assign if the MangoesInTree variable is not null that is the variable itself. That is the purpose of null coalescing operator. It helps to assign a non-nullable types with nullable types in C#.

Reading and Writing to the Console

In the previous article we discussed about the basic structure of a C# program. Today we will see reading and writing operation to the console. We will see a little more interactive sample program than the previous today. Our program will ask the user his/her name and then print a welcome message with the name of the user which he/she just enter.

To write something to the console we have two methods under System namespace, one is Write and the other is WriteLine. Only the difference between these two is, if we use WriteLine then after writing something to the console it will print a new line also but in Write method it will just print something. No new line will be printed here.

For an example if we write in the main method Console.Write(“Hello World ”); then the output should be as follows-

Hello World press any key to continue

The line “press any key to continue” indicates that the program is terminated. Instead of this method if we use Console.WriteLine(“Hello World ”); then the output should be as follows-

Hello World

press any key to continue

Here we can see that the line “press any key to continue” is in a new line. So the method Writeline prints a new line after writing something to the console.

Similarly there are to methods for reading something in the console, one is Read and the other is ReadLine. The Read method read integer type from the console and the Readline method read string type from the console. So if we write Console.ReadLine() then we have to store the returned result in a string type variable so that we can use it later in the program.

Now let’s see the code our sample program. It is as follows-

using System;
class Program
{
   static void Main()
    {
        Console.WriteLine("What is your name?");
        string name = Console.ReadLine();
        Console.WriteLine("Welcome "+ name);
    }
}

Here we can see in the MAIN method first we are printing a message asking the user’s name. Then when our next line of code executed it waits for the user input that is our read operation from the console. When the user enters something and press the Enter button then Console.Readline methos reads what is entered in the console and return it as a string type. Here we store the returned string in a string type variable named name. So what user entered in the console now stored in the variable. Then in the next line we write in the console “Welcome “concatenated with the name of the user. Here we are concatenating two string- One is “Welcome ” and the other is string type variable called name with the “+” sign in the WriteLine method.
There are actually two ways of writing something in the console. They are-
• Concatenation
• Place holder syntax
We already have seen the concatenation method of writing something to the console. Now we will see the place holder syntax in the same program. If we want to use place holder syntax in the same program then the code should be as follows-

using System;
class Program
{
   static void Main()
    {
        Console.WriteLine("What is your name?");
        string name = Console.ReadLine();
        Console.WriteLine("Welcome {0}",name);
    }
}

Here we can see in case of “+” operator we use “{0}” in the string with Welcome. This is called the place holder. When we run the program, the value of the variables that we pass after comma in the WriteLine method replaces the place holder. So if we run this piece of code we will see the same result here.
The place holder syntax is more preferable than the Concatenation process. To see how place holder syntax gives more capability let’s modify the above program. Now we will ask the user to enter his/her first name then after reading the first name we will ask for last name and after reading that we will print the first name and last name separated by a comma with the welcome message. To do that the program should be as follows –

using System;
class Program
{
   static void Main()
    {
        Console.WriteLine("What is your first name?");
        string firstname = Console.ReadLine();
        Console.WriteLine("What is your last name?");
        string lastname = Console.ReadLine();
        Console.WriteLine("Welcome {0},{1}",firstname,lastname);
    }
}

Here in the code we can see there are two place holders and there are two string type variable as well to store the first name and last name of user. When we write the welcome message in WriteLine method we use two placeholder and two variable to replace the place holder. In the same way we can use as many as place holders we required. We just have to surround the number of that place holder with curly braces. That’s why place holder syntax is more preferable than the concatenation method.

Introduction(Understand the basic structure of a c# program)

Hello Everyone!! In this series of tutorial we are going to discuss about the basic elements of C#. Like all others OOP (Object Oriented Programming) languages C# is also an OOP language that means the three qualities that make a programming language object oriented can be found in C# also. The qualities are-

  • Encapsulation
  • Polymorphism
  • Inheritance

We will understand each of this qualities in the later session of this series. In this article we will understand the basic structure of a C# program. All the sample programs of this series is going to be a Console Application and we are using Visual Studio as the IDE. So first we will learn how to open a console application in Visual Studio.

A console application is nothing but a program that can be executed in the command prompt of our Computer. To open a console application first we have to open visual studio then from the menu choose File-> New-> Project. Then another windows will pop up then in the popup window choose Visual C# in the left and you can see console application there. Choose Console Application template and give it a suitable name, you can choose the location where to save this program in your pc from here also. When you choose everything click the OK button to create the program.

OpenNewProject

When you click the OK button the program will be created and you will see the following code –

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace introduction
{
    class Program
    {
        static void Main()
        {
        }
    }
}

Now for simplicity we will remove some code from the above and make it a very basic structure of a C# program. After removing those code the above program will looks like the following-

using System;

class Program
{
    static void Main()
    {

    }
}

The above program can be said as a very basic structure of C# program. Now we will describe each line of the above program.
The first line is-
using System;

This is called the namespace declaration. A namespace is nothing but a collection of some classes, enums, structs, interfaces and delegates. What are all these we will discuss later. A namespace can hold another namespace also. For now to understand the above line we can say there are some built-in methods in this namespace called System and to use those methods and classes we have to declare the namespace by using keyword at the top. Just for an example if we want to print something in the console then we can write the following code-

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello world");
    }
}

To run the above code press Ctrl+F5. Then the command prompt should appear with the message “Hello world”.
The definition of this Writeline method is written in the namespace called System. Now if we remove the using System; line from our code then we will get an error in the line Console.WriteLine(“Hello world”);
Because now the definition of WRITELINE method is missing from our program. If we want to remove the namespace declaration then we have to write the name in the line when we use a method belongs to that namespace as follows-

class Program
{
    static void Main()
    {
        System.Console.WriteLine("Hello world");
    }
}

Namespace is used to organize our code more effectively. If you don’t use the namespace declaration at the top then each time when you use a method you have to write its namespace which is more time consuming. So the use of namespace declaration is important.
Now the next thing in our basic structure is a Class declaration. We assume that you are familiar with OOP and if you are so then you are already known to class. Like other OOP language the class declaration in C# is exactly same. Anything you write in C# is belongs to a class. There are different types of class in C#. We will discuss it later in this series. Just for now we can say any piece of code should be inside of a class. Here the name of our class is Program.
Then there is also a method named Main and it is a static method. What is static method and class we will discuss it later. Now what we have to understand is the Main method is the starting point of our program. When we run our code it start to execute each line from the beginning of Main method and end when the Main method ends. To prove this, we can declare another same method named Main2 and in this method we print another message to differentiate the two method. We can consider the following piece of code-

using System;
class Program
{
    static void Main2()
    {
        Console.WriteLine("Another Message");
    }
    static void Main()
    {
        Console.WriteLine("Hello world");
    }
}

Here if we run the program we will see that only the message “Hello world” is printed. Another method named MAIN2 is not executed. So it’s proved that our program start from Main method and terminate when the MAIN method terminates. If we want to print the 2nd message then we have to call the MAIN2 method from MAIN method before it terminates. We can do it by the following-

using System;
class Program
{
    static void Main2()
    {
        Console.WriteLine("Another Message");
    }
    static void Main()
    {
        Console.WriteLine("Hello world");
        Main2();
    }
}

Now we should be able to see both messages.
In this article we see the basic structure of a C# programming and we can sum up with the following decisions from the above discussion-
• The namespace declaration using System; indicates that you are using System namespace
• A namespace is a collection of Classes, Structs, Delegates, Enums, Interfaces and used to organize the code more effectively.
• Our program starts with the Main method and terminates when the Main method terminates.