Friday, August 19, 2011

?? operator in c# || null-coalescing

Hi,
This little comment on ?? operator in c# will give an idea how to use it.


You cannot assign NULL to any value type in c#
Is there any way to assign null to Int.The answer is NO.
For example:
           int x = NULL; //Error as you cannot assign null to a non-nullable type
instead you can use like this,
           int? x = NULL; //Runs Without error


What happens if x is assign to a variable of type int?
          int y = x; //Error
          int y = (int)x; //Error
Even if i cast it to int it wont allow to set the null to y,


Now the ?? comes into he picture.


        int y = x  ??  5;
Here,the value for x is checked (if x is null then it will assign 5 to y);
        now y will contain 5;
Suppose if i want to set the value of x you can do it ,Just simply assign x = 90;
and now,
        int y = x  ??  5;
Here the value for x is not null so the value of x is assigned to the y .
        now y will contain 90;



Tuesday, August 2, 2011

Sizeof() in c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataTypes
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
Console.WriteLine("Size of Int " + sizeof(int));
Console.WriteLine("Size of Float " + sizeof(float));
Console.WriteLine("Size of Double " + sizeof(double));
Console.WriteLine("Size of Decimal " + sizeof(decimal));
Console.WriteLine("Size of Char " + sizeof(char));
//Console.WriteLine("Size of String " + sizeof(string)); -- can't do this because string is of unknown size
}
}
}