All Type Coding

Search Here

Operators in c#

Operators 
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. There are diffrent type of operator these are givin below.
1-Arithmetic Operators 
2-Relational Operators
3- Logical Operators
4- Bitwise Operators
5- Assignment Operators
6- Misc Operators
This tutorial will explain the arithmetic, relational, and logical, bitwise, assignment and other operators one by one.

Arithmetic Operators:

Here are the most common arithmetic operators 
+  Addition,
-   Subtraction,
*   Multiplication,
/   Division  ,
% Modulus Operator and remainder of after an integer division

Arithmetic operators program  

using System; 

class Program 
{
 static void Main(string[] args)
 {
 int a = 21;
 int b = 10; 
 int c;
 c = a + b;
 Console.WriteLine("Line 1 - Value of c is {0}", c);
 c = a - b;
 Console.WriteLine("Line 2 - Value of c is {0}", c);
 c = a * b;
 Console.WriteLine("Line 3 - Value of c is {0}", c);
 c = a / b;
 Console.WriteLine("Line 4 - Value of c is {0}", c);
 c = a % b;
 Console.WriteLine("Line 5 - Value of c is {0}", c);
 c = a++;
 Console.WriteLine("Line 6 - Value of c is {0}", c);
 c = a--; 
Console.WriteLine("Line 7 - Value of c is {0}", c);
 Console.ReadLine();
 }
 }

Output :
 Line 1 - Value of c is 31
 Line 2 - Value of c is 11 
 Line 3 - Value of c is 210
 Line 4 - Value of c is 2
 Line 5 - Value of c is 1 
 Line 6 - Value of c is 21 
 Line 7 - Value of c is 22

Relational Operators

The relational operators compare values to one other. The comparison operators are =, <>, <, >, <=, and >=. All of the relational operators result in a Boolean value.
The relational operators have the following general meaning:
1- The = operator tests whether the two operands are equal.
2- The <> operator tests whether the two operands are not equal.
3- The < operator tests whether the first operand is less than the second operand.
4- The > operator tests whether the first operand is greater than the second operand.
5- The <= operator tests whether the first operand is less than or equal to the second operand.
6- The >= operator tests whether the first operand is greater than or equal to the second operand.

Relational Operators program:

 using System;

 class Program 
 {
 static void Main()
 {
 int a = 21;
 int b = 10;
 if (a == b)
 {
 Console.WriteLine("Line 1 - a is equal to b");
 }
 else
 {
 Console.WriteLine("Line 1 - a is not equal to b");
 }
 if (a < b) 

Console.WriteLine("Line 2 - a is less than b");
 }
 else
 {
 Console.WriteLine("Line 2 - a is not less than b");
 }
 if (a > b)
 {
 Console.WriteLine("Line 3 - a is greater than b");
 }
 else 
 { 
Console.WriteLine("Line 3 - a is not greater than b");
 }
 /* Lets change value of a and b */ 
 a = 5;
 b = 20;
 if (a <= b)
 {
 Console.WriteLine("Line 4 - a is either less than or equal to b");
 }
 if (b >= a) 
{
Console.WriteLine("Line 5-b is either greater than or equal to b"); 
}
}
OutPut:
Line 1 - a is not equal to b
Line 2 - a is not less than b 
Line 3 - a is greater than b 
Line 4 - a is either less than or equal to b 

Line 5 - b is either greater than or equal to b

Logical Operators

The And, Not, Or, and Xor operators, which are called the logical operators, are evaluated as follows:
For the Boolean type:
1- A logical And operation is performed on its two operands.
2- A logical Not operation is performed on its operand.
3- A logical Or operation is performed on its two operands.
4- A logical exclusive-Or operation is performed on its two operands.
Logical Operator Program:

using System; 
class Program 
{
static void Main()
{
bool a = true; 
bool b = true;
if (a && b)
{
Console.WriteLine("Line 1 - Condition is true");
}
if (a || b)
{
Console.WriteLine("Line 2 - Condition is true"); 
}
 /* lets change the value of a and b */
a = false;
b = true;
if (a && b)
{
Console.WriteLine("Line 3 - Condition is true");
 }
else 
{
 Console.WriteLine("Line 3 - Condition is not true");

if(!(a && b)) 
{
Console.WriteLine("Line 4 - Condition is true"); 
}
Console.ReadLine(); 
}
}

Output:
Line 1 - Condition is true 
Line 2 - Condition is true 
Line 3 - Condition is not true 
Line 4 - Condition is true


BitWise Operator

The c# bitwise operators I shall be covering here and are of particular interest to me in my followup post are :
1. binary OR(|) operator
2. binary AND(&) operator
3. XOR (^) operator
4. Not (~) operator
5. left shift(<<) operator
6. Right shift(>>) operator

using System;
namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 60;            /* 60 = 0011 1100 */  
            int b = 13;            /* 13 = 0000 1101 */
            int c = 0;           

             c = a & b;           /* 12 = 0000 1100 */ 
             Console.WriteLine("Line 1 - Value of c is {0}", c );

             c = a | b;           /* 61 = 0011 1101 */
             Console.WriteLine("Line 2 - Value of c is {0}", c);

             c = a ^ b;           /* 49 = 0011 0001 */
             Console.WriteLine("Line 3 - Value of c is {0}", c);

             c = ~a;               /*-61 = 1100 0011 */
             Console.WriteLine("Line 4 - Value of c is {0}", c);

             c = a << 2;     /* 240 = 1111 0000 */
             Console.WriteLine("Line 5 - Value of c is {0}", c);

             c = a >> 2;     /* 15 = 0000 1111 */
             Console.WriteLine("Line 6 - Value of c is {0}", c);
            Console.ReadLine();
        }
    }
}
When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240

Line 6 - Value of c is 15



Assignment operators

There are following assignment operators supported by C#:



Example
Try the following example to understand all the assignment operators available in C#:

using System;

    class Program
    {
        static void Main(string[] args)
        {
            int a = 21;
            int c;

            c = a;
            Console.WriteLine("Line 1 - =  Value of c = {0}", c);

            c += a;
            Console.WriteLine("Line 2 - += Value of c = {0}", c);

            c -= a;
            Console.WriteLine("Line 3 - -=  Value of c = {0}", c);

            c *= a;
            Console.WriteLine("Line 4 - *=  Value of c = {0}", c);

            c /= a;
            Console.WriteLine("Line 5 - /=  Value of c = {0}", c);

            c = 200;
            c %= a;
            Console.WriteLine("Line 6 - %=  Value of c = {0}", c);

            c <<= 2;
            Console.WriteLine("Line 7 - <<=  Value of c = {0}", c);

            c >>= 2;
            Console.WriteLine("Line 8 - >>=  Value of c = {0}", c);

            c &= 2;
            Console.WriteLine("Line 9 - &=  Value of c = {0}", c);

            c ^= 2;
            Console.WriteLine("Line 10 - ^=  Value of c = {0}", c);

            c |= 2;
            Console.WriteLine("Line 11 - |=  Value of c = {0}", c);
            Console.ReadLine();
        }
    }
OutPut:
Line 1 - =     Value of c = 21
Line 2 - +=    Value of c = 42
Line 3 - -=    Value of c = 21
Line 4 - *=    Value of c = 441
Line 5 - /=    Value of c = 21
Line 6 - %=    Value of c = 11
Line 7 - <<=    Value of c = 44
Line 8 - >>=    Value of c = 11
Line 9 - &=    Value of c = 2
Line 10 - ^=    Value of c = 0
Line 11 - |=    Value of c = 2

Misc Operator OR Ternary Operator


The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.
condition ? first_expression : second_expression;

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.
Program of ternary operator:

using System;
{
class Program 
{
 static void Main() 
{
 /* example of sizeof operator */ 
Console.WriteLine("The size of int is {0}", sizeof(int));
Console.WriteLine("The size of short is {0}", sizeof(short)); 
Console.WriteLine("The size of double is {0}", sizeof(double));
 /* example of ternary operator */ 
int a, b;
 a = 10; 
b = (a == 1) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b); 
b = (a == 10) ? 20 : 30; 
Console.WriteLine("Value of b is {0}", b); 
Console.ReadLine(); 
Output:
The size of int is 4 
The size of short is 2 
The size of double is 8 
Value of b is 30 
Value of b is 20

Type conversions in c#

 Type conversions

In CSharp type conversions are divided into two category:
1-Implicit Conversions 
Implicit casting doesn't require a casting operator no special syntax is required because the conversion is type safe and no data will be lost.
2-Explicit Conversions
Explicit casting requires a casting operator. Explicit conversions require a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. 

Conversion is the process of changing the value of one Type to another. System.Convert class provides a complete set of methods for supported conversions.
Conversions declared as implicit occur automatically, when required and Conversions declared as explicit require a cast to be called.
for Example:
1:int i = 100;
2:long j = i;

  // implicit conversion from int type to long type

Here the conversion occurred automatically. Because we converted an integer type to long type . This type of conversion is called Implicit Conversion .

for Example:
1:int i = 100;
2:long j = i;

  // implicit conversion from int type to long type
3:int i = (int)j;
  // explicit conversion from long type to int type

Here we explicitly convert long type to integer (int i= (int)j), otherwise the compiler will show compiler error - Error : Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) . This type of conversion is called Explicit Conversion .

The following example shows an explicit type conversion:

Implicit Conversion Example
using System;
class Program
{
    public static void Main()
    {
        int i = 100;

        // float is bigger datatype than int. So, no loss of
        // data and exceptions. Hence implicit conversion
        float f = i;

        Console.WriteLine(f);
    }
}


Explicit Conversion Example
using System;
class Program
{
    public static void Main()
    {
        float f = 100.25F;

        // Cannot implicitly convert float to int.
        // Fractional part will be lost. Float is a
        // bigger datatype than int, so there is
        // also a possiblity of overflow exception
        // int i = f;

        // Use explicit conversion using cast () operator
        int i = (int)f;

        // OR use Convert class
        // int i = Convert.ToInt32(f);

        Console.WriteLine(i);
    }
}


C# Type Conversion Methods

1    ToBoolean
Converts a type to a Boolean value, where possible.

2    ToByte
Converts a type to a byte.

3 ToChar
Converts a type to a single Unicode character, where possible.

4 ToDateTime
Converts a type (integer or string type) to date-time structures.

5 ToDecimal
Converts a floating point or integer type to a decimal type.

6 ToDouble
Converts a type to a double type.

7 ToInt16
Converts a type to a 16-bit integer.

8 ToInt32
Converts a type to a 32-bit integer.

9 ToInt64
Converts a type to a 64-bit integer.

10 ToSbyte
Converts a type to a signed byte type.

11 ToSingle
Converts a type to a small floating point number.

12 ToString
Converts a type to a string.

13 ToType
Converts a type to a specified type.

14 ToUInt16
Converts a type to an unsigned int type.

15 ToUInt32
Converts a type to an unsigned long type.

16 ToUInt64
Converts a type to an unsigned big integer.

Union and union all in sql server

UNION 
The UNION operator selects only distinct values by default. The UNION operator is used to combine the result-set of two or more SELECT statements.
Each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.The column names in the result-set of a UNION are usually equal to the column names in the first SELECT statement in the UNION.
Syntax:

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

For Example: let's see how to use union operator between two or more table
let'a say we have two table Unionall1 and Unionall 
Unionall1 






Unionall Table








Select * from Unionall1
union 
Select * from Unionall

The output will be like below:













UNION ALL
The SQL UNION ALL operator is used to combine the result sets of 2 or more SELECT statements. It returns all rows from the query (even if the row exists in more than one of the SELECT statements).

Each SELECT statement within the UNION ALL must have the same number of fields in the result sets with similar data types.

Syntax:

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

Let's see how to use union all 
Select * from Unionall1
union all
Select * from Unionall


The output will be like below:












Differences between UNION and UNION ALL Operators?

1-UNION removes duplicate rows, whereas UNION ALL doesn’t.

2-UNION have to perform distinct sort to remove duplicates, which makes it less faster than UNION ALL.
3-UNION is a little bit slower than UNION ALL because When use UNION, to remove the duplicate rows, sql server has to to do a distinct sort, which is time consuming. For this reason, UNION ALL is much faster than UNION.  
4-ORDER BY clause should be used only on the last SELECT statement in the UNION query.


Note: For UNION and UNION ALL to work, the Number, Data types, and the order of the columns in the select statements should be same.
Note: If you want to see the cost of DISTINCT SORT, you can turn on the estimated query execution plan using CTRL + L.

Differences between JOIN and UNION
UNION combines the result set of two or more select queries into a single result set which includes all the rows from all the queries in the UNION, where as JOIN retrieves data from two or more tables based on logical relationships between the tables.

In short, UNION combines rows from 2 or more tables, where JOIN combines columns from 2 or more tables.

Coalesce function in sql server.

COALESCE function
The COALESCE function in SQL returns the first non-NULL expression among its arguments.
Syntax:
             COALESCE ("expression 1", "expressions 2", ...)

Here Consider the Employees1 Table below. Not all employees have their First, Midde and Last Names filled. Some of the employees has First name missing, some of them have Middle Name missing and some of them last name. let's see how to use coalesce function 








Now, let's write a query that returns the Name of the Employee. If an employee, has all the columns filled - EmpFName, EmpMName and EmpLName, then we only want the EmpFName.

If the EmpFNameis NULL, and if EmpMName and EmpLName are filled then, Coalesce function returns middle name because COALESCE function in 
SQL returns the first non-NULL expression among its arguments like below.

SELECT Empid, COALESCE(EmpFName, EmpMName, EmpLName) AS Name
FROM Employees1

Output will be:










We are passing EmpFNameEmpMNameand, EmpLName columns as parameters to the COALESCE() function. The COALESCE() function returns the first non null value from the 3 columns.like above  Empid =1 has all columns filled then coalesce function return EmpFName ,Empid =3 has filled EmpLName and EmpFNameEmpMNameand is NULL Coalesce function return EmpLName
Coalesce function is very usefull.

How to replace NULL value in sql server.?

Here  We will learn about different ways to replace NULL values in SQL Server.
Let's see How to replace null.Let's consider the Employees table below. 












In previous post We have learnt writing a LEFT OUTER SELF JOIN query, which produced the following output. 










In the above image output, MANAGER column, for Sandy  rows is NULL. I want to replace the NULL value, with 'No Manager' Let''s see how to replace null value using query

1- Using ISNULL() function: 
We are passing 2 parameters to IsNULL() function. If M.EmpName returns NULL, then 'No Manager' string is used as the replacement value.

SELECT E.EmpName as Employees
ISNULL(M.EmpName,'No Manager') as Manager
FROM Employees E
LEFT JOIN Employees M
ON E.ManagerID = M.EmpID

The output will be:











2-Using CASE Statement:

SELECT E.EmpName as Employees
CASE WHEN M.EmpName IS NULL 
THEN 'No Manager' ELSE M.EmpName END as Manager
FROM Employees E
LEFT JOIN Employees M
ON E.ManagerID = M.EmpID

The output will be like below:



3-Using COALESCE() function: 
COALESCE function returns the first non-null expression in the list. If all expressions evaluate to null, then the COALESCE function will return null.

SELECT E.EmpName as Employees
COALESCE(M.EmpName, 'No Manager') as Manager
FROM Employees E
LEFT JOIN Employees M
ON E.ManagerID = M.EmpID

The output will be like above image :






SELF JOIN in Sql Server.

SELF JOIN is not a different type of JOIN. A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that qualify column names in the join condition.  It can be classified under any type of JOIN - INNER, OUTER or CROSS Joins. The above query is, LEFT OUTER SELF Join.Let's see how to use self join 

Step 1: Create a table

Create table Employees
(
Empid int primary key,
EmpName varchar(50),
ManagerId int

)

Step 2 : Insert data into Employees table
Insert into Employees values(1,'Ram',1),
 (2,'Deepa',1),
 (3,'Amit',1),
 (4,'Sandy',null),
 (5,'Ankit',3),
 (6,'Kapil',2),
 (7,'Kapil',2)

Consider Employees table shown below.









Let's say I want to get the data like below.











Select E.EmpName as Employee, M.EmpName as Manager

from Employees E
Left Join Employees M
On E.ManagerId = M.Empid

After executing the above query.the output will be above image

Using INNER JOIN


Select E.EmpName as Employee, M.EmpName as Manager

from Employees E
Inner Join  Employees M
On E.ManagerId = M.Empid

After executing the above query.the output will be like below:









Using CROSS JOIN

Select E.EmpName as Employee,M.EmpName  as Manager
from Employees E
Cross Join Employees M

Boxing and UnBoxing in c#.

Boxing is the process of converting a value type to the type object 
C# allows us to convert a Value Type to a Reference Type, and again to Value Types . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing.
Boxing
for example:
int a= 1;
Object b= a; //Boxing

Here we created a variable a  Value Type type and assigned a value to a 
The next line , we created an instance of Object and assign the value of a  to b.
Now we saw converting a value of a Value Type into a value of a corresponding Reference Type . These types of operation is called Boxing.

UnBoxing

  1: int a  = 1;
  2: Object ba  ;     //Boxing
  3: int c = (int)b;    //Unboxing

The first and second  two line shows how to Box a Value Type . The next line (int c = (int) b) shows extracts the Value Type from the Object . That is converting a value of a Reference Type into a value of a Value Type. This operation is called UnBoxing.