Chapter-2 Introduction To C#: Structure of C# Program

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

5th SEMESTER BCA DOT NET WITH C#

CHAPTER-2
INTRODUCTION TO C#
Structure of C# program:
Built in namespace
namespace declaration
{
class class_name
{
Main method()
{
Statements and expressions;
}
User defined methods
}
}

Example:
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World");
Console.Read();
}
}
}

• The first line of the program using System: - the using keyword is used to include
the System namespace in the program. A program generally has
multiple using statements.

• The next line has the namespace declaration. A namespace is a collection of classes.
The HelloWorldApplication namespace contains the class HelloWorld.

1
5th SEMESTER BCA DOT NET WITH C#

• The next line has a class declaration, the class HelloWorld contains the data and
method definitions that your program uses. Classes generally contain multiple
methods. Methods define the behaviour of the class. However, the HelloWorld class
has only one method Main.

• The next line defines the Main method, which is the entry point for all C# programs.
The Main method states what the class does when executed.

There are many keywords in Main():

public:- It is an access specifier in Main method which has global scope.

static:- It is a keyword which means object is not required to access static members so, it saves
the memory.

void:- It is a return type of the method and it doesn’t return any value.

Main:- It is a method name. It is the entry point for any C# program. Whenever we run C#
program Main() method is invoked first before any other method.

string[] args:- The string[] args is a variable that has all the values passed from the command
line.

Console.WriteLine(): Console is the class defined in System Namespace. The WriteLine() is


the output method of Console class which is used to write the text on the Console.

Console.ReadLine(): It is the method which receives the information from the users and send
it to the Console class.

/*………..*/ is a comment which is ignored by the program.

Namespace:
Namespace allows classes, structures and other items to be grouped and organized and it
removes the possibility of class naming conflicts.
• Within the namespace, all the declared class names must be uniquely named.
• The same class name can be duplicated in other namespaces.

C# data types:
A data type specifies the type of data that a variable can store such as integer, floating,
character etc.

2
5th SEMESTER BCA DOT NET WITH C#

There are 3 types of data types in C# language.

Value types:
Value type variables can be assigned a value directly. The value data types are integer-based
and floating-point based. C# language supports both signed and unsigned literals. Available
value types in C# are:
Type Description
Byte 8-bit unsigned integer
Sbyte 8-bit signed integer
Short 16-bit signed integer
Ushort 16-bit unsigned integer
Int 32-bit signed integer
Uint 32-bit unsigned integer
Long 64-bit signed integer
Ulong 64-bit unsigned integer
Float 32-bit Single-precision floating point type
Double 64-bit double-precision floating point type
Decimal 128-bit decimal type for financial and monetary
calculations
Char 16-bit single Unicode character
Bool 8-bit logical true/false value
Object Base type of all other types.

3
5th SEMESTER BCA DOT NET WITH C#

String A sequence of Unicode characters


DateTime Represents date and time

Reference Types:
Reference types do not contain the actual data stored in a variable, but they contain a reference
to the variables. In other words, they refer to a memory location.
Object type:
• Object type is the ultimate base class of all the data types in C# CTS.
• The object types can be assigned values of any other types, value types, reference types.
• Before assigning the values, it needs type conversion.
• Type checking of object type variables takes place at compile time.
Boxing:
The process of assigning or converting a value of a variable from value type to reference
(object) type is called Boxing.
Boxing is an implicit conversion process in which object type is used.
Example:
int num=10; //10 is assigned to num
object obj=num; //Boxing
Unboxing:
The process of assigning or converting a value of a variable from reference (object) type into
value type is known as Unboxing.
Unboxing is an explicit conversion.
Example:
int num=10; //10 is assigned to num
object obj=num; //Boxing
int i=(int)obj; //Unboxing
Dynamic Type:
We can store any type of value in the dynamic data type variable. Type checking for these
types takes place at the run time.
Syntax: dynamic<variable_name>=value;
Example: dynamic d=20;
String Type:
We can assign any string value to a variable using string type.

4
5th SEMESTER BCA DOT NET WITH C#

The values to a string type can be assigned using string literal in two forms, quoted and
@quoted
Example: string str= “welcome”;
@“welcome”;

Pointer type:
Pointer type variables stores the memory address of another type. It is also known as locator or
indicator that points to an address of a value.

Address Value
Pointer Variable
Symbols used in pointers:
& - Address or reference operator, used to determine the address of a variable.
*- Indirection or dereferencing operator, used to access the value of an address.

Variables
A variable is a name given to a memory location and all the operations done on the variable
effects that memory location.
In C#, all the variables must be declared before they can be used. It is the basic unit of
storage in a program. The value stored in a variable can be changed during program
execution.
Syntax: type variable_list;
Example: int i, j; or int i=1, j=2;
double d;
Rules for defining a variable:
• A variable can have alphabets. Digits and underscore.
• A variable name can start with alphabet and underscore only. It can’t starts with
digit.
• No white space is allowed with in variable name.
• A variable name must not be a keyword like char, float etc.

Types of Variables
• Local variables

5
5th SEMESTER BCA DOT NET WITH C#

• Instance variables or Non – Static Variables


• Static Variables or Class Variables
• Constant Variables
• Readonly Variables

Local Variables:
A variable defined within a block or method or constructor is called local variable.

• These variables are created when the block is entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
• The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access these variables only within that block.
C# program to demonstrate the local variables
using System;
class StudentDetails
{
// Method
public void StudentAge()
{
// local variable age
int age = 0;
age = age + 10;
Console.WriteLine("Student age is: " + age);
}
// Main Method
public static void Main(String[] args)
{
// Creating object
StudentDetails obj = new StudentDetails();
// calling the function
obj.StudentAge();
}
}
Output:

6
5th SEMESTER BCA DOT NET WITH C#

Student age is: 10

Explanation: In the above program, the variable “age” is a local variable to the function
StudentAge(). If we use the variable age outside StudentAge() function, the compiler will
produce an error as shown in below program.

Instance Variables or Non – Static Variables:

Instance variables are non-static variables and are declared in a class but outside any
method, constructor or block. As instance variables are declared in a class, these variables
are created when an object of the class is created and destroyed when the object is
destroyed. Unlike local variables, we may use access specifiers for instance variables.

// C# program to illustrate the Instance variables


using System;
class Marks
{
/* These variables are instance variables. These variables are in a class and are not inside
any function */
int engMarks;
// Main Method
public static void Main(String[] args)
{
// first object
Marks obj1 = new Marks();
obj1.engMarks = 90;
// second object
Marks obj2 = new Marks();
obj2.engMarks = 95;
// displaying marks for first object
Console.WriteLine("Marks for first object:");
Console.WriteLine(obj1.engMarks);
// displaying marks for second object
Console.WriteLine("Marks for second object:");
Console.WriteLine(obj2.engMarks);
}

7
5th SEMESTER BCA DOT NET WITH C#

}
Output :

Marks for first object:

90

Marks for second object:

95

Explanation: In the above program the variables, engMarks is an instance variables. If


there are multiple objects as in the above program, each object will have its own copies of
instance variables. It is clear from the above output that each object will have its own copy
of the instance variable.
Static Variables or Class Variables:
Static variables are also known as Class variables. If a variable is explicitly declared with
the static modifier or if a variable is declared under any static block then these variables are
known as static variables.

• These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
• Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
• Static variables are created at the start of program execution and destroyed
automatically when execution ends.
Note: To access static variables, there is no need to create any object of that class, simply
access the variable as:

class_name.variable_name;

// C# program to illustrate the static variables


using System;
class Emp {
// static variable salary
static double salary;
static String name = "Aks";

8
5th SEMESTER BCA DOT NET WITH C#

// Main Method
public static void Main(String[] args)
{
// accessing static variable
// without object
Emp.salary = 100000;
Console.WriteLine(Emp.name + "'s average salary:"
+ Emp.salary);
}
}
Output:

Aks's average salary:100000

The Syntax for static and instance variables are :


class Example

static int a; // static variable

int b; // instance variable

Constants Variables

If a variable is declared by using the keyword “const” then it is a constant variable and
these constant variables can’t be modified once after their declaration, so it’s must initialize
at the time of declaration only.

// C# program to illustrate the constant variable


using System;
class Program {
// constant variable
const float max = 50;
// Main Method
public static void Main()

9
5th SEMESTER BCA DOT NET WITH C#

{
// displaying result
Console.WriteLine("The value of max is = " + Program.max);
}
}
Output:

The value of max is = 50

Important Points about Constant Variables:


• The behavior of constant variables will be similar to the behavior of static
variables i.e. initialized one and only one time in the life cycle of a class and doesn’t
require the instance of the class for accessing or initializing.
• The difference between a static and constant variable is, static variables can be
modified whereas constant variables can’t be modified once it declared.

Read-Only Variables:
If a variable is declared by using the readonly keyword then it will be read-only variables
and these variables can’t be modified like constants but after initialization.
• It’s not compulsory to initialize a read-only variable at the time of the declaration, they
can also be initialized under the constructor.
• The behavior of read-only variables will be similar to the behavior of non-static
variables, i.e. initialized only after creating the instance of the class and once for each
instance of the class created.
Example 1: In below program, read-only variables k is not initialized with any value but
when we print the value of the variable the default value of int i.e 0 will display as follows :

//C# program to show the use of readonly variables without initializing it


using System;
class Program {
// readonly variables
readonly int k;
// Main Method
public static void Main()
{

10
5th SEMESTER BCA DOT NET WITH C#

// Creating object
Program obj = new Program();
Console.WriteLine("The value of k is = " + obj.k);
}
}
Output:
The value of k is = 0

Important Points about Read-Only Variables:


• The only difference between read-only and instance variables is that the instance
variables can be modified but read-only variable can’t be modified.
• Constant variable is a fixed value for the whole class whereas read-only variables is a
fixed value specific to an instance of class.

Parameters in C#:

Method is a collection of statements that perform some specific task and may/may not return
the result to the caller.
Methods gives the user the ability to reuse the same code which ultimately saves the
excessive use of memory, acts as a time saver and more importantly, it provides better
readability of the code.
A parameter is a named variable passed into a function or a method.
C# contains the following types of Method Parameters:
• Named Parameters
• Default or Optional Parameters
• Value Parameters
• Ref Parameters
• Out Parameters

Named Parameters
Using named parameters, you can specify the value of the parameter according to their names
not their order in the method. Or in other words, it provides us a facility to not remember
parameters according to their order.

11
5th SEMESTER BCA DOT NET WITH C#

// C# program to illustrate the concept of the named parameters


using System;
public class BCA {
// addstr contain three parameters
public static void addstr(string s1, string s2, string s3)
{
string result = s1 + s2 + s3;
Console.WriteLine("Final string is: " + result);
}
// Main Method
static public void Main()
{
// calling the static method with named
// parameters without any order
addstr(s1: "welcome", s3: "BCA", s2: "to");

}
}

Output:
Final string is: Welcome to BCA
Default Parameter:

If users are not specified values of the variables at the time of calling method then
automatically compiler receives values which were presented in the called function or method
definition.

Example: C# program to demonstrate default parameters.


using System;
class Dparam
{
public int add(int x, int y=0, int z=100)
{
return(x+y+z);
}
public static void Main(string[] args)
{
Dparam obj=new Dparam();
int a,b,c;
a=obj.add(10,20,30);
b=obj.add(50,60);

12
5th SEMESTER BCA DOT NET WITH C#

c=obj.add(10);
Console.WriteLine(“sum of three numbers=”+a);
Console.WriteLine(“sum of three numbers=”+b);
Console.WriteLine(“sum of three numbers=”+c);
}
}
Output:
sum of three numbers=60
sum of three numbers=210
sum of three numbers=110
Value Parameters:

It is also called as call by value or pass by value. It is the default parameter passing mechanism.

In this case, whatever the changes made in the method definition those will not reflect/ affect
on method call. That’s the reason original values are not modified.

Example: C# program to demonstrate value parameters.


using System;
class vparam
{
public void swap(int x, int y)
{
int temp=x;
x=y;
y=temp;
}
public static void Main(string[] args)
{
vparam obj=new vparam();
int a=100, b=200;
Console.WriteLine("before swap a is:"+a);
Console.WriteLine("before swap b is:"+b);
obj.swap(a,b);
Console.WriteLine("after swap a is:"+a);

13
5th SEMESTER BCA DOT NET WITH C#

Console.WriteLine("after swap b is:"+b);


}
}
Output:
before swap a is:100
before swap b is:200
after swap a is:100
after swap b is:200
Ref Parameter:

A reference parameter is a reference to a memory location of a variable. When you pass


parameters by reference, unlike value parameters, a new storage location is not created for
these parameters. The reference parameters represent the same memory location as the actual
parameters that are supplied to the method.

These are also called as pass by reference or call by reference.

You can declare the reference parameters using the ref keyword. The following example
demonstrates this –

Example: C# program to demonstrate reference parameters.


using System;
class rparam
{
public void swap(ref int x, ref int y)
{
int temp=x;
x=y;
y=temp;
}
public static void Main(string[] args)
{
rparam obj=new rparam();
int a=100, b=200;
Console.WriteLine("before swap a is:"+a);
Console.WriteLine("before swap b is:"+b);

14
5th SEMESTER BCA DOT NET WITH C#

obj.swap(ref a,ref b);


Console.WriteLine("after swap a is:"+a);
Console.WriteLine("after swap b is:"+b);
}
}
Output:
before swap a is:100
before swap b is:200
after swap a is:200
after swap b is:100
Out Parameter:

These are quite similar to reference parameters.

These parameters are used to return more than one value.

Out parameters transfer the data from called method to the calling method. Here can use the
“out” keyword on both method definition and calling.

Example: C# program to demonstrate out parameters.


using System;
class vparam
{
public void swap(out int x)
{
int temp=5;
x=temp;
}
public static void Main(string[] args)
{
vparam obj=new vparam();
int a=100;
Console.WriteLine("before swap a is:"+a);
obj.swap(out a);
Console.WriteLine("after swap a is:"+a);
}

15
5th SEMESTER BCA DOT NET WITH C#

}
Output:
before swap a is:100
after swap a is:5

Type Conversion:
Type conversion happens when we assign the value of one data type to another. If the data
types are compatible, then C# does automatic type conversion. If not compatible, then they
need to be converted explicitly which is known as explicit type conversion.
Type conversion is converting from one type of data to another type. It is also called as Type
Casting.
There are two types of conversions in C#. They are:
1. Implicit type conversion: Implicit casting is done automatically when passing a
smaller size type to a larger size type.
It happens when:
• The two data types are compatible.
• When we assign value of a smaller data type to a bigger data type.

Example: C# program to demonstrate implicit type conversion.


using System;
class implct
{
public static void Main(string[] args)
{
int i=10;
double d;
d=i;
Console.WriteLine(“value of i is=”+i);

16
5th SEMESTER BCA DOT NET WITH C#

Console.WriteLine(“value of d is=”+d);
Console.ReadLine();
}
}
o/p:
value of i is= 10
value of d is= 10

2. Explicit type conversion:


There may be compilation error when types not compatible with each other. These
conversions are done explicitly by users using predefined functions.
Explicit casting must be done manually by placing the type in parentheses in front of
the value and conversion happens from larger type to a smaller size type.

C# provides built-in methods for Type-Conversions as follows:

Example: C# program to demonstrate Explicit type conversion.


using System;
class expct
{
public static void Main(String[] args)
{
double d = 765.12;

17
5th SEMESTER BCA DOT NET WITH C#

// Explicit Type Casting


int i = (int)d;
Console.WriteLine("Value of i is " +i);
}
}

C# Features

C# is object oriented programming language. It provides a lot of features that are given below.

1. Simple
2. Modern programming language
3. Object oriented
4. Type safe
5. Interoperability
6. Scalable and Updateable
7. Component oriented
8. Structured programming language
9. Rich Library
10. Fast speed

1)Simple
C# is a simple language in the sense that it provides structured approach (to break the problem
into parts), rich set of library functions, data types etc.
2) Modern Programming Language
C# programming is based upon the current trend and it is very powerful and simple for building
scalable, interoperable and robust applications.
3) Object Oriented
C# is an object-oriented programming language. OOPs makes development and maintenance
easier where as in Procedure-oriented programming language it is not easy to manage if code
grows as project size grow.
4) Type Safe
C# type safe code can only access the memory location that it has permission to execute.
Therefore, it improves a security of the program.

18
5th SEMESTER BCA DOT NET WITH C#

5) Interoperability
Interoperability process enables the C# programs to do almost anything that a native C++
application can do.

6) Scalable and Updateable


C# is automatic scalable and updateable programming language. For updating our application
we delete the old files and update them with new ones.

7) Component Oriented
C# is component-oriented programming language. It is the predominant software development
methodology used to develop more robust and highly scalable applications.

8) Structured Programming Language


C# is a structured programming language in the sense that we can break the program into parts
using functions. So, it is easy to understand and modify.

9) Rich Library
C# provides a lot of inbuilt functions that makes the development fast.

10) Fast Speed


The compilation and execution time of C# language is fast.

Chapter 1 Questions:
1. What is DOT Net?
2. Explain DOT Net Framework.
3. Explain the components of DOT Net Framework.
4. Define
a. CLR
b. FCL
c. CTS
d. MSIL
e. JIT
f. Metadata
5. Explain CLR execution process with diagram.
6. Define Assemblies and explain its types.
7. Define namespace with its syntax.
8. List out the features of C#.

Chapter 2 Questions:
1. Explain the structure of C# program.
2. Explain the classification of C# datatypes.
3. Explain Boxing and Unboxing with an example.

19
5th SEMESTER BCA DOT NET WITH C#

4. What is type conversion/ Type casting?


5. Explain Implicit type conversion with an example.
6. Explain Explicit type conversion with an example.
7. Define parameters and arguments.
8. What is a variable? Mention the rules to define a variable.
9. Explain the types of Variables with examples.
10. List out the types of method parameters in C#.
11. Explain Named parameters with an example.
12. Explain Default Parameters with an example.
13. Explain Value Parameters with an example.
14. Explain Ref Parameters with an example.
15. Explain Out Parameters with an example.

20

You might also like