Saturday, 27 February 2016

Datatype conversions

In this post we will discuss
    
         Implicit Conversions
         Explicit Conversions
         Parse() and TryParse()

Type conversion is a mechanism to convert one datatype to another.Conversion is based on type compatibility and data compatibility.

Implicit Conversion :

Implicit conversion is done automatically by the compiler:
   1. When there is no loss of information if the conversion is done
   2. If there is no possibility of throwing exceptions during the conversion

It includes conversion of smaller datatype to larger datatype ,conversion of derived class to base class. This is a safe type conversion.

Example
using System;

namespace ImplicitConversion {
 class Program {
  static void Main(string[] args) {
   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:

Explicit conversion is being done by using a cast operator.

It includes conversion of larger data type to smaller data type and conversion of base class to derived classes. In this conversion information might be lost or conversion might not be succeed for some reasons. This is an un-safe type conversion.

Example

using System;

namespace ExplicitConversion {
 class Program {
  static void Main(string[] args) {
   float f = 100.25 F;

   // Use explicit conversion using cast () operator
   int i = (int) f;
   // OR use Convert class
   // int i = Convert.ToInt32(f);

   Console.WriteLine(i);

  }
 }
}

Output :100

If a number is string we can’t convert  to int then we use Parse and TryParse.

Difference between Parse and TryParse :

1. If the number is in a string format you have 2 options - Parse() and TryParse().

2. Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns a bool indicating whether it succeeded or failed.

3. Use Parse() if you are sure the value will be valid, otherwise use TryParse().

Program using Parse()

using System;

namespace arrays {
 class Program {
  static void Main(string[] args) {

   string value = "200t";
   int enternumber = int.Parse(value);
   Console.WriteLine(enternumber);

  }
 }
}

Output : throws an exception   FormatException was unhandled.

Then we can use TryParse. TryParse does not cannot throws an exception.

Program using TryParse()

using System;

namespace arrays {
 class Program {
  static void Main(string[] args) {

   string value = "200t";
   int r;
   bool enternumber = int.TryParse(value, out r);
   Console.WriteLine(enternumber);

  }
 }
}


Output :


TryParse() Example 

Wednesday, 24 February 2016

Operators


An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.C# has rich set of built-in operators and provides the following type of operators

Common operators:

Arithmetic Operators like +,-,*,/,%
Assignment Operator =,+=,-=,*=,/=,%=
Comparison Operators like ==, !=,>, >=, <, <=
Conditional Operators like &&, ||
Ternary Operator ?:
Null Coalescing Operator ??


Example:

using System;
class Program
{
    static void Main()
    {
        int a = 21;
        int b = 10;
        int c;

        Console.WriteLine("Examples of Arithmetic operators");
        c = a + b;
        Console.WriteLine(" 1 - Value of c is {0}", c);
        c = a - b;
        Console.WriteLine(" 2 - Value of c is {0}", c);
        c = a * b;
        Console.WriteLine(" 3 - Value of c is {0}", c);
        c = a / b;
        Console.WriteLine(" 4 - Value of c is {0}", c);
        c = a % b;
        Console.WriteLine(" 5 - Value of c is {0}", c);

        Console.WriteLine("Assignment operators");
        c = a;
        Console.WriteLine(" 1 - =  Value of c = {0}", c);
        c += a;
        Console.WriteLine(" 2 - += Value of c = {0}", c);
        c -= a;
        Console.WriteLine(" 3 - -=  Value of c = {0}", c);
        c *= a;
        Console.WriteLine(" 4 - *=  Value of c = {0}", c);
        c /= a;
        Console.WriteLine(" 5 - /=  Value of c = {0}", c);
        c = 200;
        c %= a;
        Console.WriteLine(" 6 - %=  Value of c = {0}", c);

        Console.WriteLine("Comparison operators");
        if (a == b)
        {
            Console.WriteLine(" 1 - a is equal to b");
        }
        else
        {
            Console.WriteLine(" 1 - a is not equal to b");
        }

        if (a < b)
        {
            Console.WriteLine(" 2 - a is less than b");
        }
        else
        {
            Console.WriteLine(" 2 - a is not less than b");
        }

        if (a > b)
        {
            Console.WriteLine(" 3 - a is greater than b");
        }
        else
        {
            Console.WriteLine(" 3 - a is not greater than b");
        }
        if (a <= b)
        {
            Console.WriteLine(" 4 - a is either less than or equal to  b");
        }

        if (b >= a)
        {
            Console.WriteLine(" 5 - b is either greater than or equal to b");
        }
        if (a !=b )
        {
            Console.WriteLine(" 6 - a is not equal  to b");
        }

        Console.WriteLine("conditional operators");

        bool d = true;
        bool e = true;

        if (d && e)
        {
            Console.WriteLine(" 1 - Condition is true");
        }

        if (d || e)
        {
            Console.WriteLine(" 2 - Condition is true");
        }
        /* lets change the value of  a and b */
        d = false;
        e = true;

        if (d && e)
        {
            Console.WriteLine(" 3 - Condition is true");
        }
        else
        {
            Console.WriteLine(" 3 - Condition is not true");
        }

        if (!(d && e))
        {
            Console.WriteLine(" 4 - Condition is true");
        }
    }
}

Ternary Operator ?:

   The ternary operator tests a condition. It compares two values. It produces a third value that depends on the result of the comparison. This can be accomplished with if-statements or other constructs.This can be accomplished with if-statements or other constructs.


Program without ternary operator:

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

        bool IsA10;

        if (a == 10)
        {
            IsA10 = true;
        }
        else
        {
            IsA10 = false;
        }

        Console.WriteLine("i == 10 is {0}", IsA10);

       
        Console.ReadLine();
    }
}
Program with ternary operator:

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

        bool IsA10 = a == 10 ? true : false;

        Console.WriteLine("i == 10 is {0}", IsA10);

    }
}


 One common use of the ternary operator is to initialize a variable with the result of the expression. It reduces multiple if-statements and nesting.
Null Coalescing Operator ??
Before discussing about null coalescing operator first we should know about nullable types in c#
Nullable types in c#
           In C# types  are divided into 2 broad categories.  
 
Value Types  - int, float, double, structs, enums etc..
Reference TypesInterface, Class, delegates, arrays etc..
By default value types are non nullable. To make them nullable use ?
int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error)
int? j = 0 (j is nullable int, so j=null is legal)
Nullable types bridge the differences between C# types and Database types
The null coalescing operator "??" uses two question marks. With it you can use a custom value for a null reference variable. It simplifies null tests.
Program without using NULL coalescing operator

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

        if (TicketsOnSale == null)
        {
            AvailableTickets = 0;
        }
        else
        {
            AvailableTickets = (int)TicketsOnSale;
        }

        Console.WriteLine("Available Tickets={0}", AvailableTickets);


    }
}

Program with using NULL coalescing operator
using System;
using System;
class Program
{
    static void Main()
    {
        int AvailableTickets;
        int? TicketsOnSale = null;

        //Using null coalesce operator ??
        AvailableTickets = TicketsOnSale ?? 0;

        Console.WriteLine("Available Tickets={0}", AvailableTickets);
        Console.ReadLine();

    }
}

Monday, 22 February 2016

Built-in types:

An important distinction that is often unmentioned when talking about C# is that most of the objects and types used are not native to C# itself. They are defined in the assemblies that are part of the .NET Framework. They're no different than the types you or I can create. But a few of these types are special. These are the "built in types," often called "primitive types,".

      These basic types are the most important of all to learn, because they are the foundation of everything you will program. These types are the most basic expression of data. 

 Basic built-in types:

1. Boolean type – Only true or false       
            This is the simplest possible type. It can only hold one of two values: true or false (1 or 0, if you prefer to think of it that way).        
eg : bool b;

2. Integral Types - sbyte, byte, short, ushort, int, uint, long, ulong, char
Integral types are all integers of varying capacities. There are two factors that define what each can hold: the size of the memory allocated, and whether or not the integer is "signed." Signed defines whether or not the type can hold negative values.
Integral types are all value types. Variables declared as any of these types hold values directly, not references to values.
eg : int i;

3. Floating Types – float and double
           Floating point types are all real numbers of varying range and precision. Both of these values are very important to understand! Range defines the maximum and minimum values the variable can hold, and precision determines the number of significant figures the variable holds.
eg : float f = 3.141f;

4. Decimal Types
The decimal keyword indicates a 128-bit data typr. Compared to floating-point types,the decimal type has more precision and a smaller range.
eg : decimal d = 3.141m;

5. String Type  
The String Type allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type.
    eg : String name =”sandhya”;

Escape Sequences in C#

   Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences.  

Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminals and printers. They are also used to provide literal representations of nonprinting characters and characters that usually have special meanings, such as the double quotation mark (").

Examples

\a Bell (alert)
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quotation mark
\" Double quotation mark
\\ Backslash
eg : String name =”\”sandhya\””;
Console.WriteLine(name );          // output “sandhya”

Verbatim Literal:

Verbatim Literal is a string with an @ symbol prefix, as in @“Hello".
Verbatim literals make escape sequences translate as normal printable characters to enhance readability.

Example:

Without Verbatim Literal : “C:\\Pragim\\DotNet\\Training\\Csharp” – Less Readable

With Verbatim Literal : @“C:\Pragim\DotNet\Training\Csharp” – Better Readable



Sunday, 21 February 2016

Reading and writing to a console



Reading from console:

 Console.ReadLine();;

Writing to console:
   
 Console.WriteLine();

There are two ways to write console
  • Concatenation
  • Place holder syntax – Most preferred

Example

Program

using System;
class Program
{
static void Main()
{
// Prompt the user for his name
Console.WriteLine("Please enter your name");
// Read the name from console
string UserName = Console.ReadLine();
// Concatenate name with hello word and print
Console.WriteLine("Hello " + UserName);
//Placeholder syntax to print name with hello word 
//Console.WriteLine("Hello {0}", UserName);
}
}



Output::



Friday, 19 February 2016

Introduction to c#


In this session we will discuss on
             Basic structure of a c# program
             Compiling & executing a c# program    
      
Basic structure of a c# program:

using System;     // namespace declaration
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
}
}            

        Namespace declaration indicates that we are using System namespace.We can use classes in .net framework.We can input and output data to command prompt using Console class.

       WriteLine is a method of the Console class and displays the message "Hello, World!" on the screen.

       using System  is a namespace  which tells to the left of the program that we are  going to make use of the code in the System .Here the console class is present inside the namespace system.

Namespace: It is a collection of classes,interfaces,enums,structs and delegates.It is used to organise your code.

      It is not necessary to use  namespace declaration .we can avoid it by using fully qualified name as below.


class Program
{
static void Main()      // method
{
System.Console.WriteLine("Hello, World!");
}
}         
       Main method is the entry point of your application.

Compiling  & executing a program:

         To run C# code, Visual Studio is the best editor. Either you can choose console based application to run program directly or you can write program on notepad and then run them on visual studio command prompt.
If you are using Visual Studio.Net for compiling and executing C# programs, take the following steps:

  • Start Visual Studio.
  • On the menu bar, choose File -> New -> Project.
  • Choose Visual C# from templates, and then choose Windows.
  • Choose Console Application.
  • Specify a name for your project and click OK button.
  • This creates a new project in Solution Explorer.
  • Write code in the Code Editor.
  • Click the Run button or press F5 key to execute the project. A Command Prompt window appears that contains the line Hello World.

You can compile a C# program by using the command-line instead of the Visual Studio IDE:

  • Open a text editor and add the above-mentioned code.
  • Save the file as helloworld.cs
  • Open the command prompt tool and go to the directory where you saved the file.
  • Type csc helloworld.cs and press enter to compile your code.
  • If there are no errors in your code, the command prompt takes you to the next line and generates helloworld.exe executable file.
  • Type helloworld to execute your program.
  • You can see the output Hello World printed on the screen.
Congratulations,you have just created your first C# application.