Basics of C Sharp c# - 1
We assume you are using Visual Studio.
Guideline 1. Must
check proper opening and closing of curly braces {}.
Guideline 2. Your
program should be properly nested.
Guideline 3. Press F5
to execute your program.
Guideline 4. If you
get exception, press Ctrl+F5 to stop execution.
Guideline 5. If you
encounter infinite loop press Ctrl+C to break execution.
Guideline 6. After
completion of each segment, must do exercises at the end of this chapter. It
will help you clear your concept and improve your programming skills.
Guideline 7. Press
F11 continuously to see how your program executes.
----------------------
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Chapter1
{
class Program
{
static void
Main(string[] args)
{
Console.WriteLine("Welcome to world of C#");
Console.ReadLine();
}
}
}
-----------
Example 2 - Data Types
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Variables_Examples
{
class Program
{
static void
Main(string[] args)
{
string
name;
string
city;
sbyte age;
int pin;
// \n is
used for line-break
Console.WriteLine("Enter your name\n");
name =
Console.ReadLine();
Console.WriteLine("Enter Your City\n");
city =
Console.ReadLine();
Console.WriteLine("Enter your age\n");
age =
sbyte.Parse(Console.ReadLine());
Console.WriteLine("Enter your pin\n");
pin =
Int32.Parse(Console.ReadLine());
//
Printing message to console
//formatting output
Console.WriteLine("==============");
Console.WriteLine("Your Complete Address:");
Console.WriteLine("============\n");
Console.WriteLine("Name = {0}", name);
Console.WriteLine("City = {0}", city);
Console.WriteLine("Age = {0}", age);
Console.WriteLine("Pin = {0}", pin);
Console.WriteLine("===============");
Console.ReadLine();
}
}
}
--------------------------
Lab :Excercise - data types
u1: Write a program to display user’s complete mailing
address. Accept user’s name, city, street, pin and house no. and store it in a
variable and display it.
Qu2: Write a program to display student information. Accept
Student’s name, Roll no, Age, class, and university name and display it on
console.
--------------------
Lab : conditional example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace even_number
{
class Program
{
static void
Main(string[] args)
{
int num;
Console.Write("Enter your number:\t");
num =
Convert.ToInt32(Console.ReadLine());
if (num %
2 == 0)
{
Console.WriteLine("{0} is Even Number", num);
}
else
{
Console.WriteLine("{0} is Odd number", num);
}
Console.ReadLine();
}
}
}
----------------------
Excercise : Conditional operator
Write a program of tax calculation. Accept money as input
from the user and calculate the tax using following pattern.
Money Percentage Total Tax
Less than 10,000 5% ?
10,000 to 100,000 8% ?
More than 100,000 8.5%
--------------------
Converto casting example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Examples
{
class Program
{
static void
Main(string[] args)
{
int
number, percentage, option;
float
result;
label:
Console.Write("\n\nEnter a number:\t");
number =
Convert.ToInt32(Console.ReadLine());
Console.Write("\nEnter Percentage Value:\t");
percentage
= Convert.ToInt32(Console.ReadLine());
result =
(float)(number * percentage) / 100;
Console.WriteLine("Percentage value is:\t{0}", result);
Console.Write("\nCalculate again press 1. To quit press
digit:\t");
option =
Convert.ToInt32(Console.ReadLine());
if (option
== 1)
{
goto
label;
}
Console.WriteLine("Press Enter for quit");
Console.ReadLine();
}
}
}
--------------------------
Lab : Loop examples
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Loop_Examples1
{
class Program
{
static void
Main(string[] args)
{
int num,
i, result;
Console.Write("Enter a number\t");
num =
Convert.ToInt32(Console.ReadLine());
for (i =
1; i <= 10; i++)
{
result
= num * i;
Console.WriteLine("{0} x {1} = {2}", num, i, result);
}
Console.ReadLine();
}
}
}
--------------------------
Loop 2 :Example 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Loop_Example2
{
class Program
{
static void
Main(string[] args)
{
int i, j;
i = 0;
j = 0;
for (i =
1; i <= 5; i++)
{
for (j
= 1; j <= i; j++)
{
Console.Write(i);
}
Console.Write("\n");
}
Console.ReadLine();
}
}
}
------------
Encapsulation
What is encapsulation?
Encapsulation is the process of hiding irrelevant data from the user. To
understand encapsulation, consider an example of a mobile phone. Whenever you
buy a mobile, you don’t see how circuit board works. You are also not
interested to know how digital signal converts into the analog signal and vice
versa. These are the irrelevant information for the mobile user, that’s why it
is encapsulated inside a cabinet.
In C# programming, we will do the same thing. We will create a cabinet
and keep all the irrelevant information in it that will be unavailable to the
user.
What is abstraction?
Abstraction is just opposite of Encapsulation. Abstraction is a
mechanism to show only relevant data to the user. Consider the same mobile
example again. Whenever you buy a mobile phone, you see their different types
of functionalities as a camera, mp3 player, calling function, recording
function, multimedia etc. It is an abstraction because you are seeing only
relevant information instead of their internal engineering.
What is Access Specifiers in
C#?
Access Specifiers defines the scope of a
class member. A class member can be variable or function. In C# there are five
types of access specifiers are available.
List
of Access Specifiers
- Public
Access Specifiers
- Private
Access Specifiers
- Protected
Access Specifiers
- Internal
Access Specifiers
- Protected
Internal Access Specifiers.
Lab : Example for Public
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Public_Access_Specifiers
{
class access
{
// String
Variable declared as public
public string
name;
// Public
method
public void
print()
{
Console.WriteLine("\nMy
name is " + name);
}
}
class Program
{
static void
Main(string[] args)
{
access ac
= new access();
Console.Write("Enter your name:\t");
//
Accepting value in public variable that is outside the class
ac.name =
Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}
Private :
The private access
specifiers restrict the member variable or function to be called outside of the
parent class. A private function or variable cannot be called outside of the
same class. It hides its member variable and method from other class and
methods
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Private_Access_Specifiers
{
class access
{
// String
Variable declared as private
private string
name;
public void
print() // public method
{
Console.WriteLine("\nMy name is " + name);
}
}
class Program
{
static void
Main(string[] args)
{
access ac
= new access();
Console.Write("Enter your name:\t");
// raise
error because of its protection level
ac.name =
Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}
Protected Access Specifiers
C#
The protected access
specifier hides its member variables and functions from other classes and
objects. This type of variable or function can only be accessed in child class.
It becomes very important while implementing inheritance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Protected_Specifier
{
class access
{
// String
Variable declared as protected
protected
string name;
public void
print()
{
Console.WriteLine("\nMy name is " + name);
}
}
class Program
{
static void
Main(string[] args)
{
access ac
= new access();
Console.Write("Enter your name:\t");
// raise
error because of its protection level
ac.name =
Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}
Example 2 protected specifier
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Protected_Specifier
{
class access
{
// String
Variable declared as protected
protected
string name;
public void
print()
{
Console.WriteLine("\nMy name is " + name);
}
}
class Program :
access // Inherit access class
{
static void
Main(string[] args)
{
Program p
= new Program();
Console.Write("Enter your name:\t");
p.name =
Console.ReadLine(); // No Error!!
p.print();
Console.ReadLine();
}
}
C# Internal Access Specifiers
The internal access specifier hides its member variables and methods
from other classes and objects, that is resides in other namespace. The
variable or classes that are declared with internal can be
access by any member within application. It is the default access specifiers
for a class in C# programming.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Internal_Access_Specifier
{
class access
{
// String Variable declared as internal
internal string name;
public void print()
{
Console.WriteLine("\nMy name
is " + name);
}
}
class Program
{
static void Main(string[] args)
{
access ac = new access();
Console.Write("Enter your
name:\t");
// Accepting value in internal
variable
ac.name = Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}
C# Protected Internal Access
Specifiers
The protected internal
access specifier allows its members to be accessed in derived class, containing
class or classes within same application. However, this access specifier rarely
used in C# programming but it becomes important while implementing inheritance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Protected_Internal
{
class access
{
// String
Variable declared as protected internal
protected
internal string name;
public void
print()
{
Console.WriteLine("\nMy name is " + name);
}
}
class Program
{
static void
Main(string[] args)
{
access ac
= new access();
Console.Write("Enter your name:\t");
//
Accepting value in protected internal variable
ac.name =
Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}
Get Set
The get set accessor or
modifier mostly used for storing and retrieving the value from the private
field. The get accessor must return a value of property type where set accessor
returns void. The set accessor uses an implicit parameter called value. In
simple word, the get method used for retrieving the value from private field
whereas set method used for storing the value in private variables.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Get_Set
{
class access
{
// String
Variable declared as private
private static
string name;
public void
print()
{
Console.WriteLine("\nMy name is " + name);
}
public string
Name //Creating Name property
{
get //get
method for returning value
{
return
name;
}
set // set
method for storing value in name field.
{
name =
value;
}
}
}
class Program
{
static void
Main(string[] args)
{
access ac
= new access();
Console.Write("Enter your name:\t");
//
Accepting value via Name property
ac.Name =
Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}
++++++++++++++++++++
Lab : Access Specifier
Write a program to
demonstrate private access specifier.
Write a program to
demonstrate get set properties
+++++++++++++++
Example for static method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Example1
{
class calculation
{
static int
num1, num2, result;
public static
void add()
{
Console.Write("Enter number 1st.\t");
num1 =
Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number 2nd.\t");
num2 =
Convert.ToInt32(Console.ReadLine());
result =
num1 + num2;
Console.Write("\nAdd = {0}", result);
Console.ReadLine();
}
}
class Program
{
static void
Main(string[] args)
{
calculation.add();
}
}
}
++++++++++++++
C# Static Method And
Variables
Whenever you write a function
or declare a variable, it doesn’t create an instance in a memory until you
create an object of the class. But if you declare any function or variable with
a static modifier, it directly creates an instance in a memory and acts
globally. The static modifier doesn't reference any object.
namespace Static_var_and_fun
{
class number
{
// Create
static variable
public static
int num;
//Create
static method
public static
void power()
{
Console.WriteLine("Power of {0} = {1}", num, num * num);
Console.ReadLine();
}
}
class Program
{
static void
Main(string[] args)
{
Console.Write("Enter a number\t");
number.num
= Convert.ToInt32(Console.ReadLine());
number.power();
}
}
}
++++++++++++++++++++++++
C# Parameters
C# parameter is nothing,
just a way to passing value to the function and then function calculate the
value and then returns appropriate results
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Understanding_Parameter
{
class Program
{
// function
with parameter
public static
int power(int num1)
{
int
result;
result =
num1 * num1;
return
result;
}
static void
Main(string[] args)
{
int pow;
// passing
arguement as parameter
pow =
Program.power(5);
Console.Write("\nPower = {0}", pow);
Console.ReadLine();
}
}
}
+++++++++++
There are two ways to
allocating space in memory. One is a value type and another is a Reference
type. When you create int, char or float type variable, it creates value type
memory allocation whereas when you create an object of a class, it creates
reference type memory allocation.
Example Value type
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Value_Type
{
class Program
{
public static
int qube(int num)
{
return num
* num * num;
}
static void
Main(string[] args)
{
int val,
number;
number =
5;
//Passing
the copy value of number variable
val =
Program.qube(number);
Console.Write(val);
Console.ReadLine();
}
}
}
+++++++++++
Example for reference type
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Reference_Parameter
{
class Program
{
public static
void qube(ref int num)
{
num = num
* num * num;
}
static void
Main(string[] args)
{
int
original = 9;
Console.Write("\ncurrent value of Original is {0}\t",
original);
Program.qube(ref original);
Console.WriteLine("\nNow the current value of Original is
{0}\t", original);
Console.ReadLine();
}
}
}
+++++++++++++++++++
C# out parameter is
such type of parameter that is declared with out keyword. It
is the same as reference parameter, that doesn’t create memory allocation.
Why use out parameter in C#?
Usually, a method returns value with return keyword.
Unfortunately, a return modifier can return only one value at a time. Sometime,
your C# program required to return multiple values from a single method. In
this situation, you need such type of function that can produce multiple output
result from a single function. The output parameter C# lets your program to
return multiple values.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace out_parameter
{
class Program
{
//Accept two
input parameter and returns two out value
public static
void rect(int len, int width, out int area, out int perimeter)
{
area = len
* width;
perimeter
= 2 * (len + width);
}
static void
Main(string[] args)
{
int area,
perimeter;
// passing
two parameter and getting two returning value
Program.rect(5, 4, out area, out perimeter);
Console.WriteLine("Area of Rectangle is {0}\t", area);
Console.WriteLine("Perimeter of Rectangle is {0}\t",
perimeter);
Console.ReadLine();
}
}
}
+++++++++++++++++++++
We all know, that we can pass the parameter to a function as an argument
but what about Main(string[] args) method? Can parameters be passed to Main()
method in C#? Yes, parameter(s) can be passed to a Main() method in C# and it
is called command line argument.
Main() method is where program stars
execution. The main method doesn’t accept parameter from any method. It accepts
parameter through the command line. It is an array type parameter that can
accept n number of parameters at runtime.
In Main(string[] args), args is a string
type of array that can hold numerous parameter.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace command
{
class Program
{
static void
Main(string[] args)
{
Console.WriteLine("First
Name is " + args[0]);
Console.WriteLine("Last Name is " + args[1]);
Console.ReadLine();
}
}
}
++++++++++++++++++++++++++
Program demonstrates difference between value type and
reference type
namespace Example1
{
class Program
{
public static
void value(int num)
{
num++;
}
public static
void reference(ref int num)
{
num++;
}
static void
Main(string[] args)
{
int num;
Console.Write("Enter a number:\t");
num =
Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n\n\tValue Type");
Console.WriteLine("----------------");
Console.Write("\nPrevious
Value:\t{0}", num);
Program.value(num);
Console.Write("\nCurrent Value:\t{0}", num);
Console.WriteLine("\n\n\n----------------");
Console.WriteLine("\tReference Type");
Console.WriteLine("--------------------");
Console.Write("\nPrevious Value:\t{0}", num);
Program.reference(ref num);
Console.Write("\nCurrent Value:\t{0}", num);
Console.ReadLine();
}
}
}
++++++++++++
Write a program
in which accept two argument as parameter from the user and returns four output
value as add, subtract, multiplication and division.
namespace Example2
{
class Program
{
public static
void parameter(int num1, int num2, out int add, out int sub, out int mul, out
float div)
{
add = num1
+ num2;
sub = num1
- num2;
mul = num1
* num2;
div =
(float)num1 / num2;
}
static void
Main(string[] args)
{
int num1,
num2;
int add,
sub, mul;
float div;
Console.Write("Enter 1st number\t");
num1 =
Convert.ToInt32(Console.ReadLine());
Console.Write("\nEnter 2nd number\t");
num2 =
Convert.ToInt32(Console.ReadLine());
Program.parameter(num1, num2, out add, out sub, out mul, out div);
Console.WriteLine("\n\n{0} + {1} = {2}", num1, num2, add);
Console.WriteLine("{0} - {1} = {2}", num1, num2, sub);
Console.WriteLine("{0} * {1} = {2}", num1, num2, mul);
Console.WriteLine("{0} / {1} = {2}", num1, num2, div);
Console.ReadLine();
}
}
}
Arrays
Write a program of
sorting an array. Declare single dimensional array and accept 5 integer values
from the user. Then sort the input in ascending order and display output.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Example1
{
class Program
{
static void
printarray(int[] arr)
{
Console.WriteLine("\n\nElements of array are:\n");
foreach
(int i in arr)
{
Console.Write("\t{0}",
i);
}
}
static void
Main(string[] args)
{
int[] arr
= new int[5];
int i;
// loop
for accepting values in array
for (i =
0; i < 5; i++)
{
Console.Write("Enter number:\t");
arr[i]
= Convert.ToInt32(Console.ReadLine());
}
Program.printarray(arr);
//sorting
array value;
Array.Sort(arr); //use array's sort function
Program.printarray(arr);
Console.ReadLine();
}
}
}
++++++++++
Write a program to
copy one array’s elements to another array without using array function.
Sorting array elements
demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Example1
{
class Program
{
static void
printarray(int[] arr)
{
Console.WriteLine("\n\nElements of array are:\n");
foreach
(int i in arr)
{
Console.Write("\t{0}", i);
}
}
static void
Main(string[] args)
{
int[] arr
= new int[5];
int i;
// loop
for accepting values in array
for (i =
0; i < 5; i++)
{
Console.Write("Enter number:\t");
arr[i]
= Convert.ToInt32(Console.ReadLine());
}
Program.printarray(arr);
//sorting
array value;
Array.Sort(arr); //use array's sort function
Program.printarray(arr);
Console.ReadLine();
}
}
}
++++++++++++++++++
Exception Handling
Try -Catch-Finally
Try Catch Finally is the
basic building block of exception handling in c#. 'Try' block
keeps the code which may raise exception at runtime. The 'catch' block
handle the exception if try block gets error and 'finally' block
executes always whether exception is raised or not. A try block may have
multiple catch blocks.
namespace Exception_Handling
{
class Program
{
static void
Main(string[] args)
{
label:
// Try
block: The code which may raise exception at runtime
try
{
int
num1, num2;
decimal result;
Console.WriteLine("Divide Program. You Enter 2 number and we return
result");
Console.WriteLine("Enter 1st Number: ");
num1 =
Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter 2nd Number: ");
num2 =
Convert.ToInt32(Console.ReadLine());
result
=(decimal)num1 / (decimal)num2;
Console.WriteLine("Divide : " + result.ToString());
Console.ReadLine();
}
//Multiple
Catch block to handle exception
catch
(DivideByZeroException dex)
{
Console.WriteLine("You have Entered 0");
Console.WriteLine("More Details about Error: \n\n" +
dex.ToString() + "\n\n");
goto
label;
}
catch
(FormatException fex)
{
Console.WriteLine("Invalid Input");
Console.WriteLine("More Details about
Error: \n\n" + fex.ToString() + "\n\n");
goto
label;
}
//Parent
Exception: Catch all type of exception
catch
(Exception ex)
{
Console.WriteLine("Othe
Exception raised" + ex.ToString() + "\n\n");
goto
label;
}
//Finally
block: it always executes
finally
{
Console.WriteLine("Finally Block: For Continue Press Enter and for
Exit press Ctrl + c");
Console.ReadLine();
}
}
}
}
+++++++++++++
Write a program to
handle NullReferenceException
and fix the error message "Object
reference not set to an instance of an object."
Unhanlded program
namespace Null_Reference_Exception
{
class Program
{
static void
Main(string[] args)
{
string
text = null;
int length
= text.Length;
Console.WriteLine(length);
Console.ReadLine();
}
}
}
Exception Handled
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Null_Reference_Exception
{
class Program
{
static void
Main(string[] args)
{
string
text = null;
try
{
int
length = text.Length;
Console.WriteLine(length);
Console.ReadLine();
}
catch (NullReferenceException nex)
{
Console.WriteLine(nex.Message);
}
Console.ReadLine();
}
}
}
++++++++++++++++++
Lab :
This program is
throwing exception IndexOutOfRangeException
. Using your skills fix this problem using
try catch block.
Unhandled exception
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Overflow_Exception
{
class Program
{
static void
Main(string[] args)
{
int num1,
num2;
byte
result;
num1 = 30;
num2 = 60;
result =
Convert.ToByte(num1 * num2);
Console.WriteLine("{0} x {1} = {2}", num1, num2, result);
Console.ReadLine();
}
}
}
++++++++++++++++
Comments
Post a Comment