C Sharp Notes PART 1
C Sharp Notes PART 1
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
Class Example_2
{
public static void Main()
{
System.Console.WriteLine("Example 2")
}
}
But while executing the program only one Main() method can be used for execution.
As in given program there are two class A and B in which each containing A Main Method. We
may write as
csc filename.cs /main:A [ for Class A Main Execution ] or,
csc filename.cs /main:B [ for Class B Main Execution ]
The using keyword is used for including the namespaces in the program. A program can
include multiple using statements.
Comments in C#
Comments are used for explaining code. Compilers ignore the comment entries. The multiline
comments in C# programs start with /* and terminates with the characters */ as shown below:
/* This program demonstrates
The basic syntax of C# programming
Language */
Member Variables
Variables are attributes or data members of a class, used for storing data. In the preceding
program, the Rectangle class has two member variables namedlength and width.
Member Functions
Functions are set of statements that perform a specific task. The member functions of a class are
declared within the class. Our sample class Rectangle contains three member
functions: AcceptDetails, GetArea and Display.
Instantiating a Class
In the preceding program, the class ExecuteRectangle contains the Main()method and
instantiates the Rectangle class.
C# command line arguments
We can pass command line arguments to C# programs. The program accept arguments in the
order of args[0], args[1] etc. The following program shows how to pass command line arguments
to the c# program. Open a new text document and copy and paste the following source code and
save the file as "NewProg.cs"
using System;
class NewProg
{
static void Main(string[] args)
{
Console.WriteLine("Arguments-1 " + args[0]+" Argument-2 "+args[1]);
Console.ReadKey();
}
}
Go to the command prompt and issue the following command for compilation.
csc NewProg.cs
After the successful compilation you will get NewProg.exe file
you will get the output like Arguments-1 test1 Argument-2 test2
A free-form language is a computer language in which coding can be positioned on any line and
still be valid. This means that a code can start on one line, end several lines down and still be a
valid statement.
For example
System.Console.WriteLine
(
“Hello”
)
___________
C # Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined
item. The basic rules for naming classes in C# are as follows:
• A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or
underscore. The first character in an identifier cannot be a digit.
• It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \.
However, an underscore ( _ ) can be used.
• It should not be a C# keyword.
C# Keywords
Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as
identifiers. However, if you want to use these keywords as identifiers, you may prefix the
keyword with the @ character.
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part and an exponent part.
You can represent floating point literals either in decimal form or exponential form.
Here are some examples of floating-point literals:
Floating-Point Literals Sequence Meaning
Double f=3.14159 /* Legal */
Double f=314159E-5 /* Legal */
Double f=510E /* Illegal: incomplete exponent */
Double f=210f /* Legal */
Double f=.e55 /* Illegal: missing integer or fraction */
Character Constants
Character literals are enclosed in single quotes, for example, 'x' and can be stored in a simple variable
of char type. A character literal can be a plain character (for example, 'x'), an escape sequence (for
example, ' \t'), or a universal character (for example, '\u02B0').
Defining Constants
Constants are defined using the const keyword. The following is the syntax for defining a constant:
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();
}
}
}
decimal 128-bit precise decimal values with 28-29 (-7.9 x 1028 to 7.9 x 1028) / 0.0M
significant digits 100 to 28
double 64-bit double-precision floating point type (+/-)5.0 x 10-324 to (+/-)1.7 x 0.0D
10308
float 32-bit single-precision floating point type -3.4 x 1038 to + 3.4 x 1038 0.0F
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. Following is an example to get the size of int type on any machine:
loopFinished = true;
C# Character Variable Type
When we talk about characters we are referring to individual letters and numbers. For example,
the letter 'a' is a character, as is the visual representation of the number '1'. Such characters may
be stored in a C# char variable. A char variable can contain one character and one character
only. It is important to be aware that a character is not limited to those in the English alphabet. A
character stored in a char variable can be Chinese, Japanese, Arabic, Cyrillic, Hebrew or any
other type of character you care to mention.
In addition, characters can be used for counting in loops and even in mathematical expressions.
To assign a character to a variable simply surround the character with singe quotes:
char myLetter = 'a';
C# provides a number of special character constants which have a special meaning when
displayed. These special constants perform such tasks as displaying tab and new lines in text.
The following table lists the characters, all of which are identified by a preceding backslash (\):
Character Constant Special Value
\n New Line
\t Tab
\0 Null
\r Carriage Return
\\ Backslash
Note that there is a special character sequence for the Backslash (\\). Because the special
characters begin with a backslash the compiler interprets any instances of a single backslash as
the pre-cursor to a special character. This raises the question of what to do if you really want a
backslash. The answer is to use the double backslash special constant sequence.
C# String Variables
In the preceding section we looked at storing individual characters in a char variable. Whilst this
works for storing a single letter or number it is of little use for storing entire words or sentences.
System.Console.WriteLine (myString);
The above example code will result in the following output:
This is line one
This is line two
As a matter of fact, any of the special characters outlined in the preceding section on
the char type may be embedded into string.
Reference Type
The 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. Using multiple variables, the reference types
can refer to a memory location. If the data in the memory location is changed by one of the
variables, the other variable automatically reflects this change in value. Example of built-
in reference types are: object,dynamic, and string.
Difference between a Value Type and a Reference Type
The Types in .NET Framework are either treated by Value Type or by Reference Type. A Value
Type holds the data within its own memory allocation and a Reference Type contains a pointer to
another memory location that holds the real data. Reference Type variables are stored in the heap
while Value Type variables are stored in the stack.
Value Type:
A Value Type stores its contents in memory allocated on the stack. When you created a Value
Type, a single space in memory is allocated to store the value and that variable directly holds a
value. If you assign it to another variable, the value is copied directly and both variables work
independently. Predefined datatypes, structures, enums are also value types, and work in the
same way. Value types can be created at compile time and Stored in stack memory, because of
this, Garbage collector can't access the stack.
_____________________
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C# has rich set of built-in operators and provides the following type of
operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
This tutorial explains the arithmetic, relational, logical, bitwise, assignment, and other operators
one by one.
Arithmetic Operators
Following table shows all the arithmetic operators supported by C#. Assume variable A holds
10 and variable B holds 20 then:
Relational Operators
Following table shows all the relational operators supported by C#. Assume variable A holds 10
and variable B holds 20, then:
Description Example
Operator
== Checks if the values of two operands are equal or not, if yes then (A == B)
condition becomes true. is not
true.
!= Checks if the values of two operands are equal or not, if values are (A != B)
not equal then condition becomes true. is true.
< Checks if the value of left operand is less than the value of right (A < B)
operand, if yes then condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal to the (A >= B)
value of right operand, if yes then condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the (A <= B)
value of right operand, if yes then condition becomes true. is true.
Logical Operators
Following table shows all the logical operators supported by C#. Assume variable A holds
Boolean value true and variable B holds Boolean value false, then:
&& Called Logical AND operator. If both the operands are non zero (A &&
then condition becomes true. B) is
false.
! Called Logical NOT Operator. Use to reverses the logical state of !(A &&
its operand. If a condition is true then Logical NOT operator will B) is
make false. true.
Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^
are as follows:
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
Assume if A = 60; and B = 13; then in the binary format they are as follows:
A = 0011 1100
B = 0000 1101
& Binary AND Operator copies a bit to the result if it exists in (A & B) = 12,
both operands. which is 0000
1100
~ Binary Ones Complement Operator is unary and has the (~A ) = 61, which
effect of 'flipping' bits. is 1100 0011 in 2's
complement due
to a signed binary
number.
<< Binary Left Shift Operator. The left operands value is A << 2 = 240,
moved left by the number of bits specified by the right which is 1111
operand. 0000
>> Binary Right Shift Operator. The left operands value is A >> 2 = 15,
moved right by the number of bits specified by the right which is 0000
operand. 1111
Assignment Operators
There are following assignment operators supported by C#:
Miscellaneous Operators
There are few other important operators including sizeof, typeof and ? :supported by C#.
as Cast without raising an exception if the cast fails. Object obj = new
StringReader("Hello");
StringReader r = obj as
StringReader;
Operator Precedence in C#
Operator precedence determines the grouping of terms in an expression. This affects evaluation
of an expression. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so the first evaluation takes place for 3*2 and then 7 is added into it.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators are evaluated first.
Show Examples
Category Operator Associativity
Type Conversions
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:
• Implicit type conversion - These conversions are performed by C# in a type-safe
manner. For example, are conversions from smaller to larger integral types and
conversions from derived classes to base classes.
•
Explicit type conversion - These conversions are done explicitly by users using the pre-
defined functions. Explicit conversions require a cast operator.
Implicit Conversion
In implicit conversion the compiler will make conversion for us without asking.
char -> int -> float is an example of data compatibility.
Complier checks for type compatibility at compilation.
Example
using System;
namespace implicit_conversion
{
class Program
{
static void Main(string[] args)
{
int num1 =20000;
int num2 =50000;
long total;
// In this the int values are implicitly converted to long data type;
//you need not to tell compiler to do the conversion, it automatically does.
total = num1 + num2;
From To
sbyte short, int, long, float, double, decimal
byte short, ushort, int, uint, long, ulong, float, double, decimal
short int, long, float, double, decimal
ushort int, uint, long, ulong, float, double, decimal
int long, float, double, decimal
uint long, ulong, float, double, decimal
long float, double, decimal
ulong float, double, decimal
float double
char ushort, int, uint, long, ulong, float, double, decimal
Explicit Conversion
In explicit conversion we specifically ask the compiler to convert the value into another data
type.
CLR checks for data compatibility at runtime.
Explicit conversion is carried out using casts. When we cast one type to another, we deliberately
force the compiler to make the transformation.
You should never expect that the cast would give you best or correct result. Casts are potentially
unsafe. Casting of big data type into small may lead to loosing of data.
Example
using System;
class ExplicitConversion
{
static void Main(string[] args)
{ double d = 5673.74;
int i;
i = (int)d; // cast double to int.
Console.WriteLine(i);
}
}
}
Boxing and Unboxing
Boxing is the process of converting a value type to the type object or to any interface type
implemented by this value type. When the CLR boxes a value type, it wraps the value inside a
System.Object and stores it on the managed heap. Unboxing extracts the value type from the
object. Boxing is implicit; unboxing is explicit.
In the following example, the integer variable i is boxed and assigned to object o.
int i = 123;
// The following line boxes i.
object o = i;
The object o can then be unboxed and assigned to integer variable i:
o = 123;
i = (int)o; // unboxing
_____________