Saturday, February 11, 2017

CSharp Primary Operators

Primary Operators in C#


C# has a rich set on operators. In this post we will discuss primary operators. They are called primary operators because they require only one operand. There are operators that take more two operand called binary operators. The ternary operator requires three operands. We will look at the binary and ternary operator in the next post. 

Operators are symbols written as part of an C# expressions or statements. When applied to the operands they performs a specific function and may transform that operand.


According to MSDN, the primary operators are as follows:



x.y: Used to access a property or a function of the left hand variable

Car c = new Car();

car.Gear = 1; //Access property of c
car.Move(); //Access function of c




f(x): Used to specify the order of operation and also used for type conversion 



Order of expression
3*(2+6)

Type Conversion

float y = 4.5f;            
Console.WriteLine("float to int {0}", (int)y);



a[x] The square brackets are used in three ways

a) To define an array
b) To access an element of an array
c) To decorate classes or members of a class with additional information called metadata

a) Define an array


int[] x = new int[10];


b) To access an element of an array


private static void ArraySample()

{
    int[] myarray = new int[10];
     for (int i = 0; i < 10; i++) {
            myarray[i] = i*5;
      }
     foreach(var element in myarray)
         Console.WriteLine(element);

}


c) To decorate classes with Attributes


using System.Runtime.InteropServices;   

class Program
{
   [DllImport("kernel32.dll")]
    public static extern bool Beep(int frequency, int duration);

    static void Main(string[] args){

             Beep(500, 2000);
     }
}


x++: Increments the variable by one. This is a shortcut for x = x+1;

for (int i = 0; i < 5; i++)
{
  Console.WriteLine(i);
}


x--: Decrements the variable by one. This is a shortcut for x = x-1;

int i=10;
while (i > 0)
{
  Console.WriteLine(i++);
}


new operator: The new operator is used to create a reference type and allocate memory to it. It is also used to create delegate. 

This operator has many forms:

Examples:

1. Cat kitty = new Cat()
2. Cat kitty = new Cat(){ age:2, color: black};
3. new {}: This notation is used to create an anonymous types
4. new T[]: Used to create an array of type T


typeof: The operand expects a Type and it returns the Type object which contains the information for that type. You cannot pass an object reference to the typeof operator as the compiler will report an error. 

Examples:

Console.WriteLine(typeof(int));    //outputs: System.Int32
Console.WriteLine(typeof(string));    //outputs: System.String
Console.WriteLine(typeof(MyType));    //outputs: ConsoleApplication1.MyType
Console.WriteLine(typeof(MyType).BaseType);    //outputs: System.Object

MyType myType = new MyType();
Console.WriteLine(typeof(myType)); //Error CS0118  'myType' is a variable but is used like a type


As you can see that the Type object is returned from the typeof operator. You can use to this information to find its base type, declaring assembly, and much more. We will more more on this when we discuss reflection in C#.


checked: The checked operator checks for overflows on an expression containing integral types. When a variable is assigned a value that it cannot hold the value is wrapped to negative. By default the run-time does not checks for such overflows so you may want to trap the result of such expressions or conversions early on.

Note that the compiler checks for the overflow assignments if the expression only contains constant values. If the expression whose value is to be assigned contains variables then the overflow will go undetected.

In the example below we are assigning the same value to both variable j and k. While the loop for j complete its 5 iterations, the result of the increment becomes invalid after the maximum value of 2147483647 is reached. After that the value wraps to negative.

In the case of variable k, we see that only 2 iterations were successful and the third one caused an exception to occur when the overflow occurs since we placed it inside the checked block.

Examples:



           Console.WriteLine("Min Value of an integer: " + Int32.MinValue);
           Console.WriteLine("Max Value of an integer: "+Int32.MaxValue);

            int j = Int32.MaxValue - 2;

            Console.WriteLine("Working with J");
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(++j);
            }

            Console.WriteLine("Working with K");
            int k = Int32.MaxValue - 2;
            for (int i = 0; i < 5; i++)
            {
                checked
                {
                    Console.WriteLine(++k);
                }
            }


Output:


Min Value of an integer: -2147483648
Max Value of an integer: 2147483647
Working with J
2147483646
2147483647
-2147483648
-2147483647
-2147483646
Working with K
2147483646
2147483647








unchecked: Any integral operation or conversion that caused an overflow is suppressed when used inside the context of unchecked keyword. 

If you assign a constant value, or an expression containing only constants to an integral datatype, the overflow is caught by the compiler. If the expression contains even a single variable (non-constant value) then the overflow goes undetected. This behavior applies for compile time and run-time and is the default behavior. 


Examples:


All constants on the right side causes the compiler to report overflow:
int x = In32.MaxValue + 1; //Error CS0220 The operation overflows at compile time in checked mode

Expression containing non-constants does not causes compiler to report an overflow nor is it reported during run-time. The value of x is printed which is outside of its range.

            int maxValue = Int32.MaxValue;

            int x = maxValue + 1; //Expression containing constants and non-constants

Output

-2147483648



default: The default keyword is used to get the default value in a switch statement.

Example:


            Console.WriteLine("Press 1,2 or 3 to select an menu");
            string pressedKey = Console.ReadKey().Key.ToString();

            switch (pressedKey) {
                case "1": Console.WriteLine(" You pressed 1"); return;
                case "2": Console.WriteLine(" You pressed 2"); return;
                case "3": Console.WriteLine(" You pressed 3"); return;
                default: Console.WriteLine(" You did not press any of the required key"); return;
            }






delegate: The use of delegate is that of a function pointer or callbacks. The declaration of a delegate is like declaring a function prototype or a method signature. 

When we say that a delegate take a function signature it means that the object referenced by a delegate is a function with a specific signature. Any function with such a signature can be referenced by such a delegate. Delegate are mostly used to define events. For now we will just look at an example of a declaring a delegate.


Sample of a delegate whose name is MyDelegate, returns void and takes two integer parameters.

public delegate void MyDelegate(int x, int y);



sizeof: The sizeof keyword is used to determine the size of a type in bytes. 

Example:

            Console.WriteLine("Size of int:"+sizeof(int));
            Console.WriteLine("Size of uint:"+sizeof(uint));
            Console.WriteLine("Size of long:"+sizeof(long));
            Console.WriteLine("Size of ulong:" + sizeof(ulong));
            Console.WriteLine("Size of double:"+sizeof(double));
            Console.WriteLine("Size of char:" + sizeof(char));


Output

Size of int:4
Size of uint:4
Size of long:8
Size of ulong:8
Size of double:8
Size of char:2

 

No comments:

Post a Comment