Introduction to C#
Programming
History of C#
• Developed by Microsoft approved by Ecma and
ISO
• Developed by Anders Hejlsberg and his team
during the development of .Net Framework.
• Based on Java and C++
• Cross-development with Visual Basic, Visual C++,
and many other .NET languages.
About C#
The following reasons make C#, a widely used professional
language:
• Modern, general purpose programming language.
• Object oriented.
• Component oriented.
• Easy to learn.
• Structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• Part of .Net Framework.
A SIMPLE C# PROGRAM
class SampleOne
{
public static void Main()
{
System.Console.WriteLine(“ C# is sharper than C++.");
}
}
Above is the simplest of all C# programs. Nevertheless, it
brings out many salient features of the language. Let us
therefore discuss the program line by line and understand
the unique features that constitute a C# program.
Class Declaration
The first line class SampleOne declares a class, which is
an object-oriented construct. C# is a true object-oriented
language and therefore, 'everything' must be placed
inside a class.
class is a keyword and declares that a new class definition
follows.
SampleOne is a C# identifier that specifies the name of
the class to be defined.
A class is a template for what an object looks like and how
it behaves.
(Details of class and object will be covered later)
The Main Method
public static void Main( )
Defines a method named Main.
Every C# executable program must include the Main() method
in one of the classes. This is the 'starting point' for executing
the program.
A C# application can have any number of classes but 'only one'
class can have the Main method to initiate the execution.
The Main Method
Public The keyword public is an access modifier that
tells the C# compiler that the Main method is accessible
by anyone.
Static The keyword static declares that the Main method
is a global one and can be called without creating an
instance of the class. The compiler stores the address of
the method as the entry point and uses this information
to begin execution before any objects are created.
void The keyword void is a type modifier that states that
the Main method does not return any value.
(but simply prints some text to the screen).
The Output Line
The only executable statement in the program is
System.Console.Writeline("C# is sharper than C++");
This has a striking resemblance to the output statement of
Java and similar to the printf of C or cout« of C++.
The WriteLine method is a static method of the Console
class, which is located in the namespace System.
This line prints the string C# is sharper than C++ to the
screen.
Every C# statement must end with a semicolon (;).
NAMESPACES
System.Console.WriteLine ();
System is the namespace (scope) in which the Console
class is located.
A class in a namespace can be accessed using the dot
operator (.) as illustrated in the statement above.
Namespaces are the way C# separate the .NET library
classes into reasonable groupings.
NAMESPACES
Names in C# belong to namespaces. They prevent
name collision and offers a manageable code
and libraries.
In the previous examples, ‘System’ is a namespace.
System.Console.Write() is a method of a class
defined in that namespace. So, the name of the
namespace is put in front to fully qualify a
name.
With the statement “using System;”, we can skip
the System part and just write Console.Write().
Hello World
using System;
class Hello {
static void Main( ) {
Console.WriteLine("Hello world");
Console.ReadLine(); // Hit enter to finish
}
}
A namespace is used to group classes into a logical set.
using System; - the using keyword is used to include the System namespace
in the program.
A namespace is a collection of classes. The HelloWorldApplication namespace
contains the class HelloWorld.
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.
The Main method specifies its behavior with the
statement Console.WriteLine("Hello World");
WriteLine is a method of the Console class defined in the System namespace.
This statement causes the message "Hello, World!" to be displayed on the
screen.
Console.ReadKey(); makes the program wait for a key press and it prevents
the screen from running and closing quickly when the program is launched from
Visual Studio .NET.
12
PROGRAM CODING STYLE
C# is a freeform language. We need not indent any lines to make the program work properly.
C# does not care where on the line we begin coding. While this may be a license for bad
programming, we should try to use this fact to our advantage for designing readable
programs. Although several alternative styles are possible, we should select one and try
to use it consistently.
For example, the statement
System.Console.WriteLine("Hello!");
can be written as
System. Console. WriteLine
("Hello!“);.
or, even as
System.Console. WriteLine
(
"Hello!”
)
ADDING COMMENTS
C# permits two types of comments, namely,
• Single-line comments
• Multiline comments
Single-line comments begin with a double backslash ( // )
symbol and terminate at the end of the line. Everything
after the // on a line is considered a comment.
Multi-line comments starts with /* characters and
terminates with */ as shown in the beginning of the
program. If we want to use multiple lines for a comment,
this type is used.
Points to remember
• C# is case sensitive.
• All statements and expression must end
with a semicolon (;).
• The program execution starts at the Main
method.
• Unlike Java, file name could be different
from the class name.
3
Literals, Variables and Data
Types
Literals, Variables and Data Types
• C# program is a collection of tokens, comments and white spaces.
• C# includes the following five types of tokens:
• Keywords
• Identifiers
• Literals
• Operators
• Punctuators
C # Keywords
abstract event namespace static
as explicit new string
base extern null struct
bool false object switch
break finally operator this
byte fixed out throw
case float override true
catch for params try
char for each private typeof
checked get protected unit
class goto public ulong
const if readonly unchecked
continue implicit ref unsafe
decimal in return ushort
default int sbyte using
delegate interface sealed value
do internal set virtual
double is short volatile
else lock sizeof void
enum long stackalloc while
Literals
Literals are value constants assigned to variables (or results of expressions) in
a program
C# Literals
Numeric Boolean Character
Literals Literals Literals
Integer Real Literals Single String
Literals Literals Literals
Integer Literals
• An integer literal refers to a sequence of digits. There are two types of
integer literals, namely,
• Decimal Integer literal
• Examples 212
• Hexadecimal Integer literal
• Example 0x4b
Real Literals
•Certain quantities are represented by numbers containing fractional parts
like 17.548. Such numbers are called real (or floating point) numbers.
• Examples 1.5f, 1.3d,2.5M
•In a real literal, decimal digits are always required after the decimal point.
For example, 1.3F is a real literal but 1.F is not.
Boolean Literals
There are two Boolean literal values: true OR false
Single Character Literals
• A single-character literal (or simply character constant) contains a single
character enclosed within a pair of single quotation marks.
• Examples ‘a’, ‘L’, ‘z’, etc.
String Literals
•A string literal is a sequence of characters enclosed between double
quotes.
•The characters may be alphabets, digits, special characters and blank
spaces.
• Examples ”hello”, “900”, “$89”, etc.
Backslash Character Literal
C# supports some special backslash character constants that are
used in output methods : escape sequences.
Backslash character literals
Constant Meaning
‘\a’ alert
‘\b’ back space
'\f’ form feed
'\n' new -line
‘\r’ carriage return
‘t’ Horizontal
'\v’ tab
vertical tab
‘\” single quote
'\”’ double quote
'\\’ backslash
'\o' null
Data types
•Data types specify the size and type of values that can be stored.
•The types in C# are primarily divided into two categories:
• Value types
• Reference types
• Value types (which are of fixed length) are stored on the stack.
• Reference types (which are of variable length) are stored on the heap.
Value type variables can be assigned a value directly.
The value types directly contain data. Some examples
are int, char, and float, which stores numbers,
alphabets, and floating point numbers.
To get the exact size of a type or a variable on a
particular platform, you can use the sizeof method. The
expression sizeof(type) yields the storage size of the
object or type in bytes.
Console.WriteLine("Size of int: {0}", sizeof(int));
Data types
Value types
Reference types
› Contain references to objects
› May be null
int i = 123; i 123
string s = "Hello world";
s "Hello world"
Data types
Value types
› Primitives int i; float x;
› Enums enum State { Off, On }
› Structs struct Point {int x,y;}
Reference types
› Root object
› String string
› Classes class Foo: Bar, IFoo {...}
› Interfaces interface IFoo: IBar {...}
› Arrays string[] a = new
string[10];
› Delegates delegate void Empty();
Data types
Value (Struct) Reference (Class)
Variable holds Actual value Memory location
Allocated on Stack, member Heap
Nullability Always has value May be null
Default value 0 null
Aliasing (in a scope) No Yes
Assignment means Copy data Copy reference
Types
Conversions
Implicit conversions
› Occur automatically
› Guaranteed to succeed
› No information (precision) loss
Explicit conversions
› Require a cast
› May not succeed
› Information (precision) might be lost
Both implicit and explicit conversions can be
user-defined
Types
Conversions
int x = 123456;
long y = x; // implicit
short z = (short)x; // explicit
double d = 1.2345678901234;
float f = (float)d; // explicit
long l = (long)d; // explicit
Memory size
To get the exact size of a type or a variable on a particular platform,
you can use the sizeof method. The expression sizeof(type) yields
the storage size of the object or type in bytes.
The following program illustrate the use of sizeof method
namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}
Out put of the above program is - Size of int: 4
Data types
C# Data Types
Value types Reference Types
User - defined Predefined User - defined
Predefined
Types Types Types
Types
Value Types
The value types of C# can be grouped into two categories namely,
• User-defined types (or complex types) and
• Predefined types (or simple type )
Complex type include struct types and enumerations.
Predefined value types (or primitive types) are further subdivided
into:
• Numeric types,
• Boolean-types, and
• Character types.
Predefined Types (Simple Types)
Simple Types
Boolean Numeric Character
Types Types Types
Decimal
Floating- Integer Types
Point Types Types
Signed Unsigned
Types Types
Categories of Simple Type Data
Boolean Type
• Boolean type is used when we want to test a particular condition
during the execution of the program.
• There are only two values that a Boolean type can take: true or
false.
Numeric Type
Numeric type is used to store numbers. It is used to store floating
point numbers, integers and decimals.
Character Type
• In order to store single characters in memory, C# provides a
character data type called char.
•The char type assumes a size of two bytes but, in fact it can hold
only a single character.
Numeric Floating-Point Types
Floating-Point
Types
float double
Floating-point data types
Floating-point data types is used to hold numbers containing fractional
parts.
Example: 27.59 and -1.375
Numeric Decimal Type
• The decimal type is a high precision, 128-bit data type that is
designed for use in financial and monetary calculations.
•It can store values in the range 1.0 x 10"28 to 7.9 x 1028 with 28
significant digits
Numeric Integer Unsigned Types
Integer types can hold whole numbers
- such as 123, 96 and 5639.
Unsigned Integers
byte ulong
ushort uint
Unsigned Integer Types
Numeric Integer Signed Types
Signed Integers
sbyte long
short int
Signed Integer types
Object Type
The Object Type is the ultimate base class for all
data types in C# Common Type System (CTS).
Object is an alias for System.Object class. The object
types can be assigned values of any other types,
value types, reference types, predefined or user-
defined types. However, before assigning values, it
needs type conversion.
When a value type is converted to object type, it is
called boxing and on the other hand, when an object
type is converted to a value type, it is
called unboxing.
Object obj; obj = 100; // this is boxing
Reference Types
The reference types can also be divided into two groups:
• User-defined (or complex) types
• Predefined (or simple) types
User-defined reference types refer to those types which we
define using predefined types. They include:
•Classes
•Delegates
•Interfaces
•Arrays
Predefined reference types include two data types:
•Object type
•String type
Pointer Type
Pointer type variables store the memory
address of another type. Pointers in C# have
the same capabilities as the pointers in C or
C++.
Syntax for declaring a pointer type is −
type* identifier;For example,
char* cptr; int* iptr;
Variables
Variables
• A variable is nothing but a name given to a storage area that our
programs can manipulate.
• Each variable in C# has a specific type, which determines the size
and layout of the variable's memory; the range of values that can be
stored within that memory; and the set of operations that can be
applied to the variable.
VARIABLES
Variable names may consist of alphabets, digits and the underscore
(_), subject to the following conditions:
1. They must begin with a char.
2. Uppercase and lowercase are distinct. This means that the
variable Total is not the same as total or TOTAL.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable names can be of any length.
VARIABLES
Which of the following are invalid variable names? If a variable is invalid,
state the reason, why is it so?
a) Gulf
b) Dot Net
c) 54java
d) string
Answer:
a) Gulf - Valid
b) Dot Net - Invalid because of space in between.
c) 54java - Invalid because of starting with digit
d) string - invalid because of keyword
Variable Definition in C#
<data_type> <variable_list>;
Example:
int i, j, k;
char c, ch;
float f, salary;
double d;
Variable Initialization in C#
<data_type> <variable_name> = value;
Example:
int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */
Initialization Of Variables
• A variable must be given a value after it has been declared but
before it is used in an expression.
• A simple method of giving value to a variable is through the
assignment statement as follows:
variableName = value;
Examples:
initialValue = 0;
yes = 'x';
•We can also string assignment expressions as shown below:
x = y = z = 0;
•It is also possible to assign a value to a variable at the time of its
declaration as follows:
type variableName = value;
Example:
namespace VariableDefinition
{
class Program
{
public static void Main(string[] args)
{
short a;
int b ;
double c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
} Put:
Out
}
a = 10, b = 20, c = 30
C# - Type Conversion
Type conversion or Type Casting is converting one type of
data to another type.
There are two types of type casting in C#:
Implicit type conversion - These conversions are
performed by C# in a type-safe manner. For example, are
conversions from smaller to larger integral types.
Explicit type conversion - These conversions are done
explicitly by users using the pre-defined functions. Explicit
conversions require a cast operator.
C# - Type Conversion
class ExplicitConversion {
static void Main(string[] args) {
double d = 5673.74;
int i; // cast double to int.
i = (int)d; Console.WriteLine(i);
Console.ReadKey();
}
}
Following are some of the C# built in Type Conversion
Methods
Method Description.
ToByte Converts a type to a byte.
ToChar Converts a type to a single Unicode character, where possible.
ToDouble Converts a type to a double type
ToInt16 Converts a type to a 16-bit integer
ToInt32 Converts a type to a 32-bit integer
ToInt64 Converts a type to a 64-bit integer.
ToString Converts a type to a string.
Example
namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
int i = 75;
float f = 53.005f;
double d = 2345.7652;
bool b = true;
Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString()); Out Put of the above
Console.ReadKey(); program is :
} 75
} 53.005
} 2345.7652
True
Example
namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
short a; int b ;
double c; /* actual initialization */
a = 10; b = 20; c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
Out Put of the above
program is :
a = 10, b = 20, c = 30
Accepting Values from User
The Console class in the System namespace provides a
function ReadLine() for accepting input from the user and
store it into a variable.
Example:
int num;
num = Convert.ToInt32(Console.ReadLine());
Accepting Values from User
using System;
class SampleEight
{
public static void Main()
{
Consote.Write(“Enter your name:");
string name = Console. ReadLine();
Console.WrtteLine (“Hello " + name);
}
}
The method
Console.Write("Enter your name: ");
String name=Console.ReadLine();
causes the execution to wait for the user to enter his name. The moment the user types his
name and presses the 'Enter' key, the input is read into the string variable name.
Method Description.
ToByte Converts a type to a byte.
ToChar Converts a type to a single Unicode character, where possible.
ToDouble Converts a type to a double type
ToInt16 Converts a type to a 16-bit integer
ToInt32 Converts a type to a 32-bit integer
ToInt64 Converts a type to a 64-bit integer.
ToString Converts a type to a string.
Constant Variables
• The variables whose values do not change during the execution of a
program
• Such variables can be made constant by using the const keyword
while initializing them.
Example:
const int ROWS = 10;
const int COLS = 20;
const int NUM = 90;
The following program demonstrates defining and
using a constant in your program:
using System;
namespace DeclaringConstants
{
class Program
{
static void Main(string[] args)
{
const double pi = 3.14159;
// constant declaration
double r, areaCircle ;
Console.WriteLine("Enter Radius: ");
r = Convert.ToDouble(Console.ReadLine());
areaCircle = pi * r * r;
Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
Console.ReadLine(); OUT PUT::
} Enter Radius:
} 3
}
Radius: 3, Area: 28.27431
USING MATHEMATICAL FUNCTIONS
C# program to compute the square root of a number:
using System;
class SampleNine
{
public static void Main()
{
double x = 5.0; //Declaration and initialization
double y; // Simple declaration
y = Math.Sqrt(x);
Console.WriteLine (" y = " + y);
}
} ,
USING MATHEMATICAL FUNCTIONS
,
This program contains more executable statements. The statement
double x = 5.0;
declares a variable x and initializes it to the value 5.0 and the statement
double y;
merely declares a variable y. Note that both of them have been declared
as double type variables, double is a data type used to represent a
floating-point number.
The statement
y = Math.Sqrt(x);
invokes the method Sqrt() of Math class which is a part of System
namespace. The program produces following output:
y = 2.23606
SCOPE OF VARIABLES
The scope of a variable is the region of code within which the variable can be
accessed.
C# defines several categories of variables. They include:
• Static variables
• Instance variables
• Array elements
• Value parameters
• Reference parameters
• Output parameters
• Local variables
DECLARATION OF VARIABLES
Declaration does three things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. The place of declaration (in the program) decides
the scope of the variable.