Showing posts with label Beginners. Show all posts
Showing posts with label Beginners. Show all posts

C# Methods : In Depth With Example

01:47 Add Comment
Since so long we have seen overview of basic programming structure of C#. In that we need to cove most important aspect of any programming language, we call it as Methods. Methods hide working of code that need to be performed repeatedly. We can call methods need to perform specific peace of code again and again. So it performs abstraction and code re-usability reducing the work of programmers.

C#-Methods-In Depth-With-Example

Before we move on further one must understand the structure of methods. This will make you understand better how programing structure is.

Defining Methods In C#

(Parameter List)
{
//body/code/ logic of methode
}

  • Access Specifiers:
    Access specifies denote wheather your class will be accessible to which elements. Mostly 3 access specifiers are used viz. Public, Private and protected. You can read here in more detail about access specifiers here.
  • Return Type:
    Return type defines what method is going to return some value, if yes then you need to define the type of value. Blow Used define method type we have created maxoftwo method that is going to return integer value(int). So whenever any method return any value such as int, float, double, string. If method is not returning any value then it must be marked as void.
  • Method Name:
    Method name is the name we will use for accessing that method. If we have class program with object name p. Under program we have method name called as abc(); So while accessing that method abc() is the name we will use. We can see this in user-define method example after sometime. But as some implied rules generally method name must be something that define it's function. Some logical name must be provided.
  • Parameter List :
    Parameter list is the argument that sometime required by methods. Some system define as well as user define methods require an argument to pass on in order to get the desire result from that method. But this parameters are option for methods. If method not reuqire it just leave that round bracket blank.
Methods are most important part of class and it defines the behavior of the class. All action about what class is all about which function must be perform by class is determine by methods define within that class. There are 2 type if class :
  • System Define Methods:
    This methods are usually defined by programming system itself. They are part of programing package and their definitions is already define by system. 
    Example:
    We generally use Console.WriteLine(); and Console.ReadLine(); are 2 system define methods. WriteLine(); is used to print the parameters as text that display while executing the program on runtime.
    On the other hand ReadLine(); is used to take input from user unless system encounter Enter command.
    Printing text on runtime and Accepting data from user it define by Console class methods namely WritLine() And ReadLine(); Programmer just need to user it properly. Like there are many methods are define by system to help programmer making work easier for them.
  • User Define Methods :
    This methods are also called as custom methods. This methods are not a System defined they are define for different costume purpose.
    Example:
    Let's understand this with the help of an example. In the program below we have created method called maxoftwo accepting 2 parameters for comparing 2 numbers. This is user define method that we have access through class object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
public class Program
{
public int maxoftwo(int a, int b)
{
int res;

if(a>b)
{
res=a;
}
else
{
res=b;
}
return res;
}

public static void Main(string[] args)
{
int a=100,b=200;
int res;
Program p= new Program();
res= p.maxoftwo(a,b);

Console.WriteLine("Max Value is {0}",res);
Console.WriteLine();
}
}
}
Output :

Max Value is 200
In the example above code Program is the class where method maxoftwo resides. For accesing the same we user the period sign. But before that we need to create object p. We created object busing new keyword.  After doing this we can access method using
objectname.methodename(parameter);
 in our code check this code for above expression:
 p.maxoftwo(a,b);

Encapsulation In C# With Example

05:59 Add Comment
Encapsulation is most important part of Object oriented programming. Basic meaning of Encapsulation is the packing of data and functions into a single component. The features of encapsulation are supported using classes in most object-oriented programming languages. This words might seems to be complex to understand. There is one more concept called as abstraction that need to be taken care of while understanding encapsulation.

Also Read : Loop In C# Programming With An Example


Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction. Do not get confuse. Read example below.

Just take a real life example: Car is an entity/class that driver drive. Starting the car, changing hear, accelerate it and so on and so forth. Let's say in programming terms this activities like starting car, changing gears and accelerate car and break are methods. So driver know what this methods do, but he really don't know how this method works. In another words driver know by pressing the hand break or the other break car will stop. But on mechanical part of it he don't know what actually happens in engine of the car to apply the breaks.

From above example we can understand that function of the car are encapsulated in class called car for make it working from different methods like accelerate, break. Here what that methods are doing actually will abstraction. Since driver know what is the function but he/she do not know what actually happened.


Here accessibility is also an important aspect of object oriented programming,Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. C# supports the following access specifiers:
  • public
  • private
  • protected
  • internal
If you have not noticed we have used public access specifier from first program itself. while we user main method in every code it start like this:

public static void main(string[] args)
{
//your code
}
We will see each of them how they differ with example:

Public Access specifier:

Public access specifier denote the compiler that that class methods and member variables are accessible to other function and objects. Public member can be accessible out side the class also. Let's take an example: We will create 2 class one is Circle and another is executecircle :

using System;
using System.Collections.Generic;
namespace Encapsulatio_Demo
{
    class Circle
    {
        //member variable of class circle
        public double radius ;
        const double pi = 3.1421; // this is constant variable in C# it's value once assign cannot be changed.
        public double AreaOfCircle()
        {
            return  pi * (redius * redius);
        }
        public void display()
        {
            Console.WriteLine("Area of the Circle "+AreaOfCircle()+" having Radius "+radius );
        }
    } 
    class ExecuteCircle
    {
        static void Main(string[] args)
        {
            Circle c = new Circle();
            c.radius = 10;
            c.display();
            Console.ReadLine();
        }
    }
}
Output will Be as follows:
Area of the Circle 314.21 having Radius 10 
In the above example Class Circle variables and method are declared as public. Hence they can be accessible in class ExecuteCircle. We have access the radius variable through object of class Circle i.e c.radius = 10; Here we are assigning the of radius. We have also displayed the output using Circle class method from c.display();

Private Access specifier:

Private access specifier do not allow other class or functions or objects to access their member variable and functions. Only function of the same class can access  it's private members. Let's take same example. Here is code:
using System;
using System.Collections.Generic;
namespace Encapsulatio_Demo
{
    class Circle
    {
        //member variable of class circle
        public double radius=10 ;
        const double pi = 3.1421; // this is constant variable in C# it's value once assign cannot be changed.
        public double AreaOfCircle()
        {
            return  pi * (redius * redius);
        }
        public void display()
        {
            Console.WriteLine("Area of the Circle "+AreaOfCircle()+" having Radius "+radius );
        }
    } 
    class ExecuteCircle
    {
        static void Main(string[] args)
        {
            Circle c = new Circle();
            c.AreaOfCircle();
            c.display();
            Console.ReadLine();
        }
    }
}

Output will Be as follows:
Area of the Circle 314.21 having Radius 10 
Here is we have not change much since methods cannot be private, because if we make them private they even cannot accessible by object of the same class. So methods have no meaning. If you try c.redius=10; this line will give an error and will not execute. Since we have marked it private. Try and change method accessibility as private then in second class where you are calling methods will be shown as error. Since private methods cannot be accessible outside the class Circle.

Protected Access Specifier:

Protected access specifier allow the child class to access access it's base class member variable and methods. We will see in detail in upcoming concept of Inheritance.

Internal Access Specifier:

Internal access specifier expose the classes exist in the same namespace or some call it as assembly. You can access one variable in another class present in same assembly once that variable is makerd internal. Check the output of below program for the same:
using System;
using System.Collections.Generic;
namespace Encapsulatio_Demo
{
    class Circle
    {
        //member variable of class circle
        internal double radius;
        const double pi = 3.1421; // this is constant variable in C# it's value once assign cannot be changed.
        public double AreaOfCircle()
        {
            return pi * (radius * radius);
        }
        public void display()
        {
            Console.WriteLine("Area of the Circle " + AreaOfCircle() + " having Radius " + radius);
        }
    }
    class ExecuteCircle
    {
        static void Main(string[] args)
        {
            Circle c = new Circle();
            c.radius = 10;
            c.display();
            Console.ReadLine();
        }
    }
}

Output will Be as follows:
Area of the Circle 314.21 having Radius 10  
So here we have done with concept of encapsulation. Don't miss our upcoming tutorial.  This are very important concept. This is concept on which interviewer will play with your mind. Stay tuned for more. You have any query or suggestion do comment below. Thank you for reading.

Loop In C# Programming With An Example

03:25 Add Comment
In previous article we have seen brief description of conditional statements which are back bone of programming. Here today we will see loop in C# programming and will see it with example. Speaking in layman term loops are used for task that need to perform representatively unless certain condition remains true and stop when that condition becomes false.


In programming languages loops are also important as conditional statements. Let me explain this with an simple example. If I will tell you to write program for printing 1 to 100 without loop statement. It will be very tedious task. Like this there are very different real-time task that need to be performed at that time loops becomes too handy for that.

C# provide following loops to handle different looping requirement:

While Loop: 

While loop is very simple of all. It simply execute the statement until condition becomes false.

Following is Syntax for the same:

while(condition expression)
{
//Statement
}

Let's take very simple example of writing tables of 5. Here the code for the same:

using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        { int a=5, b=1,c;//declaration and assignment of variables
            Console.WriteLine("Table Of 5 :");
            while (b<=10)//condition expression
            {
                //statements
                c = a * b;
                Console.WriteLine(a+" X "+b+" = "+c);
                b++;
            }
        }
    }
}
Output of the following code will be:
Table Of 5 :
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
Press any key to continue . . .
In above program there are three variables viz a,b and c. Value of variable a is constant "a=5". On the other hand value of b keeps on changing till 10. Both values held by a and b are multiplied and their output is then stored in variable c. We can write a single program in all loop but every loop have their own purpose. Now we will see 

Do........While Loop:

Do while loop is similar to while loop. There is only one difference between while and do..while loop. In While loop there is always first condition is checked and then it entered in to loop. 

Syntax of Do.....While Loop:

do{
//statement
}while(condition expression);
Here notice we end/terminate the do..while loop after while condition.
using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 5;
           do
            {
                Console.WriteLine("This statement will execute only in do...while loop............");
            } while (a > 10) ;
        }
    }
}
On the other hand Do.. While loop one time statement is executed and then condition is checked. I am sure you are confused. So we will take on example:

I will write both program but both will have wrong false value at the first iteration itself.

Example of While Loop:
using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 5;
            while (a>10)
            {
                Console.WriteLine("This statement will not execute............");
            }
        }
    }
}
This program will execute without any error but you will not get anything as output.

Example of Do While Loop:
using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 5;
           do
            {
           Console.WriteLine("This statement will execute only in do...while loop............");            } while (a > 10) ;
        }
    }
}

Output:
This statement will execute only in do...while loop............ 
Here even if the condition is false then too the statement in the body of the loop get executed once. Now let's take same example for this loop is as follows:

using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 5,b=1,c;
           do
            {
                c = a * b;
                Console.WriteLine(a + " X " + b + " = " + c);
                b++;
            } while (b <= 10) ;
        }
    }
}

Output:
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
Press any key to continue . . .
For Loop:

This loop is most preferred loop in programming and most easy to write. Let's first see the syntax of the For loop:

Syntax:

for(initialization, condition, increment)
{
//Statement(s);
}
For loop is divided into 3 parts viz. Initialization, Condition, Increment:

for (int b = 1; b <= 10; b++)
  • Initialization:
    When for loop get executed, it first enter into initialization part and it only executed once. This step allow you to declare variable that have only scope in that for loop. In above example when loop started execution then it will first check int b=1; Here we initialize b and assign the value to it. Here semicolon indicate end of initialization phase termination or end of initialization phase
  • Condition:
    In next step it evaluate conditional expression. After the first iteration only Condition and increment phase of loop is checked. Initialization is ignored. In condition evaluated to be true then loop body get executed, or else it will be skipped and control jumps to the net statement. In above example we are checking for value of variable b if it less then or equal to 10 then only it will execute loop body or else it will skip loop and transfer control to next statement.
  • Increment:
    In this phase after checking for condition you can increment or decrement value of variable. Here we are incrementing value of variable b by 1. 
So this way loop iterated though itself until condition becomes false. Let's take that example of table of 5 using for loop:

using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 5,c;
            for (int b = 1; b <= 10; b++)
            {
                c = a * b;
                Console.WriteLine(a + " X " + b + " = " + c);
            }
        }
    }
}
Output:
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

So here all are loop provided in C# is explained with example. One foreach loop is remaining but we will see that in detail at later sessions. But when we talk about Loop we need to know some 

Loop Control Statement:

Loop control statements are used for changing th normal execution of the programming sequences of loop. There are two control statement provided by C# as follows:

break statement:

Break statement is used as for throwing control out of the loop. When compiler encounters beak keyword it will transfer control out of loop. Let's take the example we will initialize one variable with value of 1 and we will increment value by 1 each time we will terminate the loop once value of variable is 5 using break statement.
using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 1;
            while (a<10)
            {
                Console.WriteLine("Value of A is "+a);
                a++;
                if (a>5)
                {
                    break;
                }
            }
            Console.WriteLine("This will execute once break statement terminate the loop.....");
        }
    }
}
Output:
Value of A is 1
Value of A is 2
Value of A is 3
Value of A is 4
Value of A is 5
This will execute once break statement terminate the loop.....
continue statement:
 This statement will skip the intimidate next statement then it will pass control back to condition expression. And then it will evaluate. In this example we will increment the value of variable by one and when value of that variable is 5 I don't want to print it. Other then that we will print all the values:

using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 1;
            while (a < 10)
            {
                if (a == 5)
                {
                    a++;
                    continue;
                }
                Console.WriteLine("Value of A is " + a);
                a++;
            }
        }
    }
}

Output:

Value of A is 1
Value of A is 2
Value of A is 3
Value of A is 4
Value of A is 6
Value of A is 7
Value of A is 8
Value of A is 9
Press any key to continue . . . 
Check on the output, value of variable 5 is not printed.  So when it enter in condition when we check a==5 after that it will increment value of a by 1 and then continue statement transfer control directly to loop statement.

Infinite Loop:
There are sometimes condition arises where by mistake we write code such a way that condition expression always remains true then loop will run forever. This kind of loop. For example:

using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 1;
            while (a==1)
            {
                Console.WriteLine("This is infinite loop......");
            }
        }
    }
}
When you execute above code, it will execute forever unless you do not stop it manually.

With this we are all gone through what is loops and what types of loop C# provide. We have also seen what are loop control statement and concept of infinite loop, all of this with an example. Do comment below if you find this article useful or have nay query thanks for reading.

C# Conditional Statement: With Example

07:21 Add Comment
Conditional Statements and Loops are most important aspect of any programming language. Every programming language offer same set of conditional structure. IF Statement, IF...ELSE Statement, Nested IF Statement, Switch Statement. Beside this C# also provide loop statement.

Also Read:  Type Conversion Or Type Casting In C# With Examples

Conditional statement control for flow of program based on certain condition. Where as Loop also control program flow but they repeats the programming statement till the condition remains true.

Condition Statement:

First we will start with conditional statements. For understanding this statement you first need to understand basic flow of Conditional statement. Here is basic flow we have tried to explain diagrammatically. 

IF Statement:

If statement is simplest conditional statement that we use in day to day life. Programming becomes easy when we compare this things with real world scenario. We take day to day decision using this type thinking only. 
Example: If I will buy xyz thing then what will be it's cost. If it cost below $20 then only I will buy this thing.

In programming also we need to avoid certain conditions to get fulfill. Here is syntax for simple if statement:
if(boolean_expression)
{
 //this statement will only execute when boolean_expression is true.
}
Let's take above situation and covert it into programming scenario.
using System;
using System.Collections.Generic;
namespace Type_of_if
{
    class Person
    {
        static void Main(string[] args)
        {
            int expense = 10;// You have 20$ at your exposure
            if (expense > 20)// Check if expense is more then 20$ then you can purchase more items
            {
                Console.WriteLine("You cannot buy more..........");
            }
            Console.WriteLine("You can buy more..........");
        }
    }
}

Output:

 You can buy more..........

In above example class person act as real person that is in supermarket and have amount of 20$ to spend for his daily needs. In this if condition, person check for expense variable every time he buy any item i.e. total sum is less then $20 if it more then that then he will not buy. If you change value of variable expense to greater then 20 say 22 then will show you output as:

You cannot buy more..........

IF.......ELSE Statement:

In above example we have only evaluated one condition. If this... but in real life situation we always check for if not this........ then that. Suppose that person need some more cash for buying more stuff but have used his entire $20 amount. Then what to do? Everyone have debit card with us now days. So if person runs out of money then So this condition in above condition can be integrated as follows:

using System;
using System.Collections.Generic;

namespace Type_of_if
{
    class Person
    {
        static void Main(string[] args)
        {
            int expense = 22;// This is your expense

            if (expense < 20)// Check if expense is less then 20$ then you can purchase more items
            {
                Console.WriteLine("You have still money left...........");
            }
            else// if expense is more then $20 then you can use debit card
            {
                Console.WriteLine("You have to use debit card now.....");
            }
        }
    }
}

Output
You have to use debit card now.....

IF.......ELSE....IF

In above condition if person have more then two choices to make then we can use IF.....ELSE....IF. It is also known as IF...ELSE ladder. Let's say person have $20 cash and debit card and vouchers for the specific store, where is is doing shopping. Then his preference will be if amount is less then $20 then spend $20 if less then $ 30 voucher worth of $30 and still if bill is more then that but less then $50 he will use debit card having balance $50. But we always make our case safe. So if amount is more then $50 will say you have to use two option combine.

Here is programmatic implementation of above condition:

using System;
using System.Collections.Generic;
namespace Type_of_if
{
    class Person
    {
        static void Main(string[] args)
        {
            int expense = 15;// This is your expense
            if (expense < 20)// Check if expense is less then 20$ then you can purchase more items
            {
                Console.WriteLine("You have used money ...........");
             
            }
            else if(expense <30)
            {
                Console.WriteLine("You vouchers are used ");
             
            }
            else if(expense < 50)
            {
                Console.WriteLine("You have used your debit card....... ");
            }
            else
            {
                Console.WriteLine("You have to use all of them..... ");
            }
        }
    }
}

Also Read: C# Data Type In Detail

SWITCH Statement: 

Switch statement also work like if...else..if statement that we saw above. You can also write the above program using switch statement. But I'll take different example this time. We all know grading system in school that we used to get out exam score. Will write simple program in Switch case for the same.

First you need to learn basic syntax for switch statement :

switch(expression) {
   case constant-expression  :
      statement;
      break;
   case constant-expression  :
      statement(s);
      break;
   default :
   statement(s);
}

Program is as follows:
using System;
using System.Collections.Generic;
namespace Type_of_if
{
    class Person
    {
        static void Main(string[] args)
        {
            char result;
            Console.WriteLine("Enter Your Grade from A OR B OR C OR D OR F");
            result = Convert.ToChar(Console.ReadLine());
         
            switch (result)
            {
                case 'A':
                    Console.WriteLine("You have got 75% and above");
                    break;
                case 'B':
                    Console.WriteLine("You have got less then 75% ");
                    break;
                case 'C':
                    Console.WriteLine("You have got 60% and above");
                    break;
                case 'D':
                    Console.WriteLine("You have got less then 60% and above");
                    break;
                case 'F':
                    Console.WriteLine("Better Luck Next Time");
                    break;
                default:
                    Console.WriteLine("Invalid input");
                    break;
            }
        }
    }
}
The program is self explanatory. But you need to know if you input alphabet small or any other then A OR B OR C OR D OR F you will get out put as invalid input. Hence we can say switch case is case sensitive. You can run it and check by your self. 

The?:operator OR Ternary operator:

This is popularly known as ternary operator. It can be used in place of IF..... ELSE statement. It works same as IF... ELSE. 

Syntax:

Exp1 ? Exp2 : Exp3;


In this operator ? is conditional operator. And expression one is evaluated as boolean expression. Let's see simple example.
using System;
using System.Collections.Generic;
namespace Type_of_if
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 10;
            string classfy;
            classfy = (a > 0) ? "positive" : "Negative";
            Console.WriteLine("Variable A is classify as "+classfy+" number");
        }
    }
}

Output:
Variable A is classify as positive number
In above example we have just classify if variable a having value 10 is positive or negative.

So here all conditional operators/ statements are explained with example. We are trying out best to make you understand program in laymen term. If you still have any doubt or any query feel free to comment below. Thanks fro reading.

Type Conversion Or Type Casting In C# With Examples

10:55 Add Comment
We have already seen C# is strictly type language. As I have explained earlier it do not convert one type to another type that directly. There are specific ways of doing so. This procedure is called type conversion. We will see type conversion in c# with examples so you will get better understanding.

Refer to this: C# Data Type In Detail


In programming programmer need to sometime manipulate variables or convert one type to another type. For doing this process of converting one type to another is called Type conversion or type casting. There are 2 types of type conversion:

Implicit Type Conversion:
Implicit type conversion perform by system automatically you don’t have to do anything. You just assign one variable to another variable type and other all things will be taken care C# compiler. Lets see an example:


using System;
namespace TypeConversion
{
   class ImplicitConversion
   {
      static void Main(string[] args)
      {
     
         float f = 75.12546f;
         double d = f;
        
         Console.WriteLine("This is float value :"+f);
         Console.WriteLine("This is double value :"+d);
         Console.WriteLine("This is double value type converted to string type"+d.ToString());
         Console.ReadKey();
           
      }
   }
}

Here is the output of the program:

Executing the program....
This is float value :75.12546
This is double value :75.1254577636719
This is double value type converted to string type75.1254577636719

In above example compiler converted float type to double type automatically. You can also see we have used .ToString() method to print the double value. Since string is alphanumeric and larger than Double type it can accept almost all type. But it was reverse then it will give you error.

Explicit Type Conversion:
As name suggest you have to explicitly tell compiler to convert one value type to another value type. You can do it by 2 ways. Let’s see an example for the same:


using System;
namespace TypeConversion
{
   class ExplicitConversion
   {
      static void Main(string[] args)
      {
         int i = 75;
         float f = 53.005f;
         int convert=(int)f;
         double d = 2345.7652155478;
         float convertftod=(float)d;

         Console.WriteLine("This is integer value "+i);
         Console.WriteLine("This is Float value "+f);
         Console.WriteLine("Converted float to int "+convert);
         Console.WriteLine("This is double value "+d);
         Console.WriteLine("Converted doule to float "+convertftod);
         Console.ReadKey();
           
      }
   }
}


The output if this program is :

Executing the program....

This is integer value 75
This is Float value 53.005
Converted float to int 53
This is double value 2345.7652155478
Converted doule to float 2345.765

Here int is smaller type then float. Hence to convert the float into integer type we have exclusively instructed the complier by (int). By this compiler forcefully convert float type to int. As you can see .005 values has been truncated y compiler since integer type do not support precision values. Similarly the case with double converted to float. You can see only first 3 values after precision have been taken and value hereafter has been truncated. Since compiler converting larger type to smaller type there is always some values that loss during conversion.

Now we move on to most important part that actually useful in real life:
We are going to see how to take user input in program and manipulate it then show it as display output.
We are going to take following thing from user as input:
First Name
Last Name
Salary
Age
Self-Description
And display user his info as output.


using System;
namespace UserInputApplication
{
   class UserInput
   {
      static void Main(string[] args)
      {
          //Defining Variable
         string fName,lName,describtion;
         int age;
         double sal;
        
         //When user input the value it will initialized
         Console.writeLine(“Enter Your First Name :\n”);
         fName=Console.ReadLine();
         Console.writeLine(“Enter Your Last Name :\n”);
         lName=Console.ReadLine();
         Console.writeLine(“Tell us something about you :\n”);
         describtion=Console.ReadLine();
         Console.writeLine(“Enter Your Age:\n”);
         age=Convert.ToInt32(Console.ReadLine());
         Console.writeLine(“Enter Your Salary :\n”);
         sal=Convert.ToDouble(Console.ReadLine());
        
         Console.WriteLine("Hello"+fName+" "+lName+"nice to know you. You age is "+age+" All we know about you is "+describtion+"And your salary is "+sal);
         Console.ReadKey();
      }
   }
}


Output of this program is:

Enter Your First Name :
Dharmesh
Enter Your Last Name :
Khatri
Tell us something about you :
I am programmer and blogger
Enter Your Age:
24
Enter Your Salary :
20000

You must have noticed for accepting first name and last name and description we just assign value to variable. While accepting age and Salary we need to convert to int and float type. Why is that so? Is it necessary? The answer is as follows:
When Console.ReadLine() method accept data from the user it will by default accept the data as String format. So assigning String type to string, there is no need of conversion. But while assigning string to integer or float will be problem. Hence we have to convert it into respective data types.
Here are list of methods that can used for Type Conversion:

ToBoolean()
ToByte()
ToChar()
ToDateTime()
ToDecimal()
ToDouble()
ToInt16()
ToInt32()
ToInt64()
ToSbyte()
ToSingle() //Converts a type to a small floating point number.
ToString()
ToUInt16()
ToUInt32()
ToUInt64()

The names itself are self-explanatory of converting methods. You can check yourself by using them as we have used in above program.

So here we have seen all implicit type conversion explicit type conversion user type conversion with an example. If you have any query comment below. Thanks for reading stay tuned for more.