
C# is a simple, modern, general-purpose, object-oriented programming language developed by Microsoft within its .NET initiative led b...
Everything is in this blog
C# is a simple, modern, general-purpose, object-oriented programming language developed by Microsoft within its .NET initiative led b...
C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and approved by European Computer Manufac...
In this chapter, we will discuss the tools required for creating C# programming. We have already mentioned that C# is part of .Net f...
Before we study basic building blocks of the C# programming language, let us look at a bare minimum C# program structure so that we ca...
C# is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that ...
The varibles in C#, are categorized into the following types: Value types Reference types Pointer types Value Type Value type v...
Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#, type casting has two forms: ...
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, wh...
The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. ...
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C# has rich set of built-in...
Decision making structures requires the programmer to specify one or more conditions to be evaluated or tested by the program, along w...
There may be a situation, when you need to execute a block of code several number of times. In general, the statements are executed s...
Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical package'. Encapsulation,...
A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main. To ...
Replace these every slider sentences with your featured post descriptions.Go to Blogger edit html and find these sentences.Now replace these with your own descriptions.
Replace these every slider sentences with your featured post descriptions.Go to Blogger edit html and find these sentences.Now replace these with your own descriptions.
Replace these every slider sentences with your featured post descriptions.Go to Blogger edit html and find these sentences.Now replace these with your own descriptions.
using System; namespace HelloWorldApplication { class HelloWorld { static void Main(string[] args) { /* my first program in C# */ Console.WriteLine("Hello World"); Console.ReadKey(); } } }When this code is compiled and executed, it produces the following result:
Hello WorldLet us look at the various parts of the given program:
using System; namespace RectangleApplication { class Rectangle { // member variables double length; double width; public void Acceptdetails() { length = 4.5; width = 3.5; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } } class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); } } }When the above code is compiled and executed, it produces the following result:
Length: 4.5 Width: 3.5 Area: 15.75
using System;The using keyword is used for including the namespaces in the program. A program can include multiple using statements.
/* This program demonstrates
The basic syntax of C# programming
Language */
Single-line comments are indicated by the '//' symbol. For example,}//end class Rectangle
Reserved Keywords | ||||||
---|---|---|---|---|---|---|
abstract | as | base | bool | break | byte | case |
catch | char | checked | class | const | continue | decimal |
default | delegate | do | double | else | enum | event |
explicit | extern | false | finally | fixed | float | for |
foreach | goto | if | implicit | in | in (generic modifier) | int |
interface | internal | is | lock | long | namespace | new |
null | object | operator | out | out (generic modifier) | override | params |
private | protected | public | readonly | ref | return | sbyte |
sealed | short | sizeof | stackalloc | static | string | struct |
switch | this | throw | true | try | typeof | uint |
ulong | unchecked | unsafe | ushort | using | virtual | void |
volatile | while | |||||
Contextual Keywords | ||||||
add | alias | ascending | descending | dynamic | from | get |
global | group | into | join | let | orderby | partial (type) |
partial (method) |
remove | select | set |
Type | Represents | Range | Default Value |
---|---|---|---|
bool | Boolean value | True or False | False |
byte | 8-bit unsigned integer | 0 to 255 | 0 |
char | 16-bit Unicode character | U +0000 to U +ffff | '\0' |
decimal | 128-bit precise decimal values with 28-29 significant digits | (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 | 0.0M |
double | 64-bit double-precision floating point type | (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 | 0.0D |
float | 32-bit single-precision floating point type | -3.4 x 1038 to + 3.4 x 1038 | 0.0F |
int | 32-bit signed integer type | -2,147,483,648 to 2,147,483,647 | 0 |
long | 64-bit signed integer type | -923,372,036,854,775,808 to 9,223,372,036,854,775,807 | 0L |
sbyte | 8-bit signed integer type | -128 to 127 | 0 |
short | 16-bit signed integer type | -32,768 to 32,767 | 0 |
uint | 32-bit unsigned integer type | 0 to 4,294,967,295 | 0 |
ulong | 64-bit unsigned integer type | 0 to 18,446,744,073,709,551,615 | 0 |
ushort | 16-bit unsigned integer type | 0 to 65,535 | 0 |
using System; namespace DataTypeApplication { class Program { static void Main(string[] args) { Console.WriteLine("Size of int: {0}", sizeof(int)); Console.ReadLine(); } } }When the above code is compiled and executed, it produces the following result:
Size of int: 4
object obj; obj = 100; // this is boxing
dynamic <variable_name> = value;For example,
dynamic d = 20;Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time.
String str = "Tutorials Point";A @quoted string literal looks as follows:
@"Tutorials Point";The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter.
type* identifier;For example,
char* cptr; int* iptr;We will discuss pointer types in the chapter 'Unsafe Codes'.
using System; namespace TypeConversionApplication { 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(); } } }When the above code is compiled and executed, it produces the following result:
5673
Sr.No | Methods & Description |
---|---|
1 | ToBoolean Converts a type to a Boolean value, where possible. |
2 | ToByte Converts a type to a byte. |
3 | ToChar Converts a type to a single Unicode character, where possible. |
4 | ToDateTime Converts a type (integer or string type) to date-time structures. |
5 | ToDecimal Converts a floating point or integer type to a decimal type. |
6 | ToDouble Converts a type to a double type. |
7 | ToInt16 Converts a type to a 16-bit integer. |
8 | ToInt32 Converts a type to a 32-bit integer. |
9 | ToInt64 Converts a type to a 64-bit integer. |
10 | ToSbyte Converts a type to a signed byte type. |
11 | ToSingle Converts a type to a small floating point number. |
12 | ToString Converts a type to a string. |
13 | ToType Converts a type to a specified type. |
14 | ToUInt16 Converts a type to an unsigned int type. |
15 | ToUInt32 Converts a type to an unsigned long type. |
16 | ToUInt64 Converts a type to an unsigned big integer. |
using System; namespace TypeConversionApplication { class StringConversion { 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()); Console.ReadKey(); } } }When the above code is compiled and executed, it produces the following result:
75 53.005 2345.7652 True
Type | Example |
---|---|
Integral types | sbyte, byte, short, ushort, int, uint, long, ulong, and char |
Floating point types | float and double |
Decimal types | decimal |
Boolean types | true or false values, as assigned |
Nullable types | Nullable data types |
<data_type> <variable_list>;Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas.
int i, j, k; char c, ch; float f, salary; double d;You can initialize a variable at the time of definition as:
int i = 100;
variable_name = value;Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a constant expression as:
<data_type> <variable_name> = value;Some examples are:
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'. */It is a good programming practice to initialize variables properly, otherwise sometimes program may produce unexpected result.
using System; namespace VariableDefinition { 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(); } } }When the above code is compiled and executed, it produces the following result:
a = 10, b = 20, c = 30
int num; num = Convert.ToInt32(Console.ReadLine());The function Convert.ToInt32() converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format.
int g = 20;But following is not a valid statement and would generate compile-time error:
10 = 20;
212 /* Legal */ 215u /* Legal */ 0xFeeL /* Legal */ 078 /* Illegal: 8 is not an octal digit */ 032UU /* Illegal: cannot repeat a suffix */Following are other examples of various types of Integer literals:
85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */
3.14159 /* Legal */ 314159E-5L /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */While representing in decimal form, you must include the decimal point, the exponent, or both; and while representing using exponential form you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.
Escape sequence | Meaning |
---|---|
\\ | \ character |
\' | ' character |
\" | " character |
\? | ? character |
\a | Alert or bell |
\b | Backspace |
\f | Form feed |
\n | Newline |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\ooo | Octal number of one to three digits |
\xhh . . . | Hexadecimal number of one or more digits |
using System; namespace EscapeChar { class Program { static void Main(string[] args) { Console.WriteLine("Hello\tWorld\n\n"); Console.ReadLine(); } } }When the above code is compiled and executed, it produces the following result:
Hello World
"hello, dear" "hello, \ dear" "hello, " "d" "ear" @"hello dear"
const <data_type> <constant_name> = value;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; Console.WriteLine("Enter Radius: "); r = Convert.ToDouble(Console.ReadLine()); double areaCircle = pi * r * r; Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle); Console.ReadLine(); } } }When the above code is compiled and executed, it produces the following result:
Enter Radius: 3 Radius: 3, Area: 28.27431
Operator | Description | Example |
---|---|---|
+ | Adds two operands | A + B = 30 |
- | Subtracts second operand from the first | A - B = -10 |
* | Multiplies both operands | A * B = 200 |
/ | Divides numerator by de-numerator | B / A = 2 |
% | Modulus Operator and remainder of after an integer division | B % A = 0 |
++ | Increment operator increases integer value by one | A++ = 11 |
-- | Decrement operator decreases integer value by one | A-- = 9 |
Operator | Description | Example |
---|---|---|
== | Checks if the values of two operands are equal or not, if yes then condition becomes true. | (A == B) is not true. |
!= | Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (A <= B) is true. |
Operator | Description | Example |
---|---|---|
&& | Called Logical AND operator. If both the operands are non zero then condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. | !(A && B) is true. |
p | q | p & q | p | q | p ^ q |
---|---|---|---|---|
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
Operator | Description | Example |
---|---|---|
& | Binary AND Operator copies a bit to the result if it exists in both operands. | (A & B) = 12, which is 0000 1100 |
| | Binary OR Operator copies a bit if it exists in either operand. | (A | B) = 61, which is 0011 1101 |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. | (A ^ B) = 49, which is 0011 0001 |
~ | Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. | (~A ) = 61, which is 1100 0011 in 2's complement due to a signed binary number. |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. | A << 2 = 240, which is 1111 0000 |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. | A >> 2 = 15, which is 0000 1111 |
Operator | Description | Example |
---|---|---|
= | Simple assignment operator, Assigns values from right side operands to left side operand | C = A + B assigns value of A + B into C |
+= | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand | C += A is equivalent to C = C + A |
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand | C -= A is equivalent to C = C - A |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand | C *= A is equivalent to C = C * A |
/= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand | C /= A is equivalent to C = C / A |
%= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand | C %= A is equivalent to C = C % A |
<<= | Left shift AND assignment operator | C <<= 2 is same as C = C << 2 |
>>= | Right shift AND assignment operator | C >>= 2 is same as C = C >> 2 |
&= | Bitwise AND assignment operator | C &= 2 is same as C = C & 2 |
^= | bitwise exclusive OR and assignment operator | C ^= 2 is same as C = C ^ 2 |
|= | bitwise inclusive OR and assignment operator | C |= 2 is same as C = C | 2 |
Operator | Description | Example |
---|---|---|
sizeof() | Returns the size of a data type. | sizeof(int), returns 4. |
typeof() | Returns the type of a class. | typeof(StreamReader); |
& | Returns the address of an variable. | &a; returns actual address of the variable. |
* | Pointer to a variable. | *a; creates pointer named 'a' to a variable. |
? : | Conditional Expression | If Condition is true ? Then value X : Otherwise value Y |
is | Determines whether an object is of a certain type. | If( Ford is Car) // checks if Ford is an object of the Car class. |
as | Cast without raising an exception if the cast fails. | Object obj = new StringReader("Hello"); StringReader r = obj as StringReader; |
Category | Operator | Associativity |
---|---|---|
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
Statement | Description |
---|---|
if statement | An if statement consists of a boolean expression followed by one or more statements. |
if...else statement | An if statement can be followed by an optional else statement, which executes when the boolean expression is false. |
nested if statements | You can use one if or else if statement inside another if or else if statement(s). |
switch statement | A switch statement allows a variable to be tested for equality against a list of values. |
nested switch statements | You can use one switch statement inside another switch statement(s). |
Exp1 ? Exp2 : Exp3;Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
Loop Type | Description |
---|---|
while loop | It repeats a statement or a group of statements while a given condition is true. It tests the condition before executing the loop body. |
for loop | It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
do...while loop | It is similar to a while statement, except that it tests the condition at the end of the loop body |
nested loops | You can use one or more loop inside any another while, for or do..while loop. |
Control Statement | Description |
---|---|
break statement | Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. |
continue statement | Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. |
using System; namespace Loops { class Program { static void Main(string[] args) { for (; ; ) { Console.WriteLine("Hey! I am Trapped"); } } } }When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but programmers more commonly use the for(;;) construct to signify an infinite loop.
using System; namespace RectangleApplication { class Rectangle { //member variables public double length; public double width; public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.length = 4.5; r.width = 3.5; r.Display(); Console.ReadLine(); } } }When the above code is compiled and executed, it produces the following result:
Length: 4.5 Width: 3.5 Area: 15.75In the preceding example, the member variables length and width are declared public, so they can be accessed from the function Main() using an instance of the Rectangle class, named r.
using System; namespace RectangleApplication { class Rectangle { //member variables private double length; private double width; public void Acceptdetails() { Console.WriteLine("Enter Length: "); length = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Enter Width: "); width = Convert.ToDouble(Console.ReadLine()); } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); } } }When the above code is compiled and executed, it produces the following result:
Enter Length: 4.4 Enter Width: 3.3 Length: 4.4 Width: 3.3 Area: 14.52In the preceding example, the member variables length and width are declared private, so they cannot be accessed from the function Main(). The member functions AcceptDetails() and Display() can access these variables. Since the member functions AcceptDetails() and Display() are declared public, they can be accessed from Main() using an instance of the Rectangle class, named r.
using System; namespace RectangleApplication { class Rectangle { //member variables internal double length; internal double width; double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.length = 4.5; r.width = 3.5; r.Display(); Console.ReadLine(); } } }When the above code is compiled and executed, it produces the following result:
Length: 4.5 Width: 3.5 Area: 15.75In the preceding example, notice that the member function GetArea() is not declared with any access specifier. Then what would be the default access specifier of a class member if we don't mention any? It is private.
<Access Specifier> <Return Type> <Method Name>(Parameter List) { Method Body }Following are the various elements of a method:
class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } ... }
using System; namespace CalculatorApplication { class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } static void Main(string[] args) { /* local variable definition */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //calling the FindMax method ret = n.FindMax(a, b); Console.WriteLine("Max value is : {0}", ret ); Console.ReadLine(); } } }When the above code is compiled and executed, it produces the following result:
Max value is : 200You can also call public method from other classes by using the instance of the class. For example, the method FindMax belongs to the NumberManipulator class, you can call it from another class Test.
using System; namespace CalculatorApplication { class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if(num1 > num2) result = num1; else result = num2; return result; } } class Test { static void Main(string[] args) { /* local variable definition */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //calling the FindMax method ret = n.FindMax(a, b); Console.WriteLine("Max value is : {0}", ret ); Console.ReadLine(); } } }When the above code is compiled and executed, it produces the following result:
Max value is : 200
using System; namespace CalculatorApplication { class NumberManipulator { public int factorial(int num) { /* local variable declaration */ int result; if (num == 1) { return 1; } else { result = factorial(num - 1) * num; return result; } } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); //calling the factorial method Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6)); Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7)); Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8)); Console.ReadLine(); } } }When the above code is compiled and executed, it produces the following result:
Factorial of 6 is: 720 Factorial of 7 is: 5040 Factorial of 8 is: 40320
Mechanism | Description |
---|---|
Value parameters | This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. |
Reference parameters | This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument. |
Output parameters | This method helps in returning more than one value. |