Professional Documents
Culture Documents
Chapter-2 Introduction To C#: Structure of C# Program
Chapter-2 Introduction To C#: Structure of C# Program
Chapter-2 Introduction To C#: Structure of C# Program
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.
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.ReadLine(): It is the method which receives the information from the users and send
it to the Console class.
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#
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#
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#
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#
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 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.
7
5th SEMESTER BCA DOT NET WITH C#
}
Output :
90
95
• 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;
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:
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.
9
5th SEMESTER BCA DOT NET WITH C#
{
// displaying result
Console.WriteLine("The value of max is = " + Program.max);
}
}
Output:
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 :
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
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#
}
}
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.
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.
13
5th SEMESTER BCA DOT NET WITH C#
You can declare the reference parameters using the ref keyword. The following example
demonstrates this –
14
5th SEMESTER BCA DOT NET WITH C#
Out parameters transfer the data from called method to the calling method. Here can use the
“out” keyword on both method definition and calling.
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.
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
17
5th SEMESTER BCA DOT NET WITH C#
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.
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.
9) Rich Library
C# provides a lot of inbuilt functions that makes the development 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#
20