Fundaments of C Sharp Note 1
Fundaments of C Sharp Note 1
C# Programming
.Net Framework Overview
VB C++ C# JScript …
Web Forms
Win Forms
(ASP.NET)
Visual Studio.NET
7
Strong Programming Features of C#
8
Strong Programming Features of C#
Boolean Conditions
Automatic Garbage Collection
Standard Library
Assembly Versioning
Properties and Events
Delegates and Events Management
Easy-to-use Generics
Indexers
Conditional Compilation
Simple Multithreading
LINQ and Lambda Expressions
Integration with Windows
9
Creating Hello World Program
A C# program consists of the following parts
−
◦ Namespace declaration
◦ A class
◦ Class methods
◦ Class attributes
◦ A Main method
◦ Statements and Expressions
◦ Comments
Creating Hello World Program
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 World
Creating Hello World Program
Let us look at the various parts of the given program −
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.
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 behavior of the
class. However, the HelloWorld class has only one
method Main.
Creating Hello World Program
Let us look at the various parts of the given program −
Thenext 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 next line /*...*/ is ignored by the compiler and it is
put to add comments in the program.
TheMain method specifies its behavior with the
statement Console.WriteLine("Hello World");
Creating Hello World Program
Let us look at the various parts of the given program −
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.
Thelast line Console.ReadKey(); is for the VS.NET Users.
This 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.
Syntax
Case-sensitive
Whitespace has no meaning
◦ Sequences of space, tab, linefeed,
carriage return
Semicolons are used to
terminate statements (;)
Curly braces {} enclose
code blocks
Unlike Java, program file name could be different
from the class name.
Visual Studio 2017 IDE
16
Using Visual Studio.NET
Types of projects
◦ Console Application
◦ Windows Application
◦ Web Application
◦ Web Service
◦ Windows Service
◦ Class Library
◦ ...
Using Visual Studio.NET
Windows
◦ Solution Explorer
◦ Class View
◦ Properties
◦ Output
◦ Task List
◦ Object Browser
◦ Server Explorer
◦ Toolbox
Using Visual Studio.NET
Building
Debugging
◦ Break points
References
Saving
Using Visual Studio.NET
Compiling and Executing the Program
if you are using Visual Studio.Net for compiling and executing C# programs, take
the following steps −
if you are using Visual Studio.Net for compiling and executing C# programs,
take the following steps −
Open the command prompt tool and go to the directory where you
saved the file.
If there are no errors in your code, the command prompt takes you
to the next line and generates helloworld.exe executable file.
You can see the output Hello World printed on the screen.
Statements, Expressions, Variables
and Data types
Statements & Expressions
Statements
are used to accomplish simplest
tasks in C#
forms simplest C# operations.
can be single line or Span to
multiple lines.
does not necessarily return a
value.
CS 1001 25
Statements & Expressions Contd...
CS 1001 27
Statements & Expressions Contd...
Examples for expressions
Result is assigned to
variable
areaOfCircle = (3.14*radius*radius);
Expression
Expressions in Test Conditions
if (num1 > num2)
CS 1001 28
Comments
Can be used to document what the program does
and what specific blocks or lines of code do.
The C# compiler ignores comments
You can include them anywhere in a program
without affecting your code.
◦ Single line comments
// for single line comments
Signed short
short 2 -32768 32767
integer
Unsigned
ushort 2 0 65535
short
Unsigned
uint 4 0 4294967295
integer
Immutable
string 20+ n/a n/a "Hello World"
character array
Represents an
instant in time,
typically 00:00:00 23:59:59 14:289:35
DateTime 8
expressed as a 01/01/0001 31/12/9999 08/05/2010
date and time of
day.
Variables in C#
To get the exact size of a type or a variable
on a particular platform, you can use the
sizeof method.
using System;
namespace DataTypeApplication {
class Program {
static void Main(string[] args) {
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}
Variables in C#
Following is an example to get the size of int type on any
machine −
using System;
namespace DataTypeApplication {
class Program {
static void Main(string[] args) {
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}
Variables in C#
Reference Type
The reference types do not contain the actual
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.
object obj;
obj = 100; // this is boxing
Variables in C#
Dynamic Type
You can store any type of value in the dynamic data type variable.
Type checking for these types of variables takes place at run-time.
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.
Variables in C#
String Type
The String Type allows you to assign any string values to a variable. The
string type is an alias for the System.String class. It is derived from
object type. The value for a string type can be assigned using string
literals in two forms: quoted and @quoted.
For example,
@"Tutorials Point";
type* identifier;
For example,
char* cptr;
int* iptr;
Variables in C#
Defining Variables
◦ <data_type> <variable_list>;
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;
Variables in C#
Initializing Variables
The general form of initialization is −
variable_name = value;
Variables can be initialized in their declaration.
<data_type> <variable_name> = value;
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();
}
}
}
Variables in C#
Accepting Values from User
int num;
num = Convert.ToInt32(Console.ReadLine());
Variables in C#
Accepting Values from User
1. Boolean Literal
There are two Boolean literal values:
Example:
100 //decimal
0x123f //hexadecimal
072 //octal
1000 //integer
100u //uint
1000 //long
10ul //ulong
Literals in C#
Real Literal
Real literals are used to write values of types
10.15 //double
100.72f //float
1.45d //double
1.44m //decimal
e23 //exponent. Means 1023
Literals in C#
Character Literal
Examples:
string a = "string, literal"; // string,
literal
string b = @"string, literal"; // string,
literal
string c = "string \t literal"; // string
literal
string d = @"string \t literal"; //
string \t literal
Literals in C#
Null Literals
Examples:
int x = null;
if (x == null)
Console.WriteLine("This is null");
Enumeration in C#
An enumeration is used in any
programming language to define a
constant set of values.
For example, the days of the week can
namespace ConsoleApplication1{
public enum Days { Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, Sunday }
class Program {
static void Main(string[] args) {
Days day = Days.Monday;
Console.WriteLine((int)day);
Console.ReadLine();
}
}
}
Enumeration in C#
Console.ReadLine();
}
Operators in C#
Operators are symbols that are used to
perform operations on operands. Operands
may be variables and/or constants.
For example, in 2+3, + is an operator that is
double x;
x = 50.05;
int a=5,c,b,d;
c=d=b=a;
Operators in C#
Basic Assignment Operator
using System;
namespace Operator{
class AssignmentOperator {
public static void Main(string[] args) {
int firstNumber, secondNumber;
// Assigning a constant to variable
firstNumber = 10;
Console.WriteLine("First Number = {0}", firstNumber);
// Assigning a variable to another variable
secondNumber = firstNumber;
Console.WriteLine("Second Number = {0}", secondNumber);
}
}
}
Operators in C#
Basic Assignment Operator
For example,
int x = 5;
int y = 10;
int z = x + y;// z = 15
Operators in C#
C# Arithmetic Operators
Modulo Operator
% 16 % 3 evaluates to 1
(Remainder)
Operators in C#
using System;
namespace Operator{
class ArithmeticOperator {
public static void Main(string[] args){
double firstNumber = 14.40, secondNumber = 4.60, result;
int num1 = 26, num2 = 4, rem;
result = firstNumber + secondNumber;
Console.WriteLine("{0} + {1} = {2}", firstNumber, secondNumber, result);
result = firstNumber - secondNumber;
Console.WriteLine("{0} - {1} = {2}", firstNumber, secondNumber, result);
C# Relational Operators
Operator Operator Name Example
namespace Operator{
class LogicalOperator{
public static void Main(string[] args) {
bool result;
int firstNumber = 10, secondNumber = 20;
// OR operator
result = (firstNumber == secondNumber) || (firstNumber > 5);
Console.WriteLine(result);
// AND operator
result = (firstNumber == secondNumber) && (firstNumber > 5);
Console.WriteLine(result);
}
}
}
Operators in C#
! Logical Negation (Not) Inverts the value of a boolean
using System;
namespace Operator
{
class UnaryOperator
{
public static void Main(string[] args)
{
bool flag = true;
C# unary operators
Operator Operator Name Description
result = +number;
Console.WriteLine("+number = " + result);
result = -number;
Console.WriteLine("-number = " + result);
result = ++number;
Console.WriteLine("++number = " + result);
result = --number;
Console.WriteLine("--number = " + result);
}
}
}
Operators in C#
The increment (++) and decrement (--) operators
can be used as prefix and postfix.
Console.WriteLine((number++));
Console.WriteLine((number));
Console.WriteLine((++number));
Console.WriteLine((number));
}
}
}
Operators in C#
We can see the effect of using ++ as prefix and postfix. When
++ is used after the operand, the value is first evaluated and
then it is incremented by 1. Hence the statement
Console.WriteLine((number++));
Console.WriteLine((++number));
prints 12.
operands.
It is a shorthand for if-then-else statement.
namespace Operator
{
class TernaryOperator
{
public static void Main(string[] args)
{
int number = 10;
string result;
result = (number % 2 == 0)? "Even " : "Odd ";
Console.WriteLine("{0} is {1}", number, result);
}
}
}
Operators in C#
}
}
}
Operators in C#
using System;
namespace Operator{
class BitOperator {
public static void Main(string[] args) {
int firstNumber = 10;
int secondNumber = 20;
int result;
result = firstNumber ^ secondNumber;
Console.WriteLine("{0} ^ {1} = {2}", firstNumber,secondNumber, result);
result = firstNumber << 2;
Console.WriteLine("{0} << 2 = {1}", firstNumber, result);
result = firstNumber >> 2;
Console.WriteLine("{0} >> 2 = {1}", firstNumber, result);
}
}
}
Operators in C#
Compound Assignment Operators
number |= 14;
Console.WriteLine(number);
number ^= 12;
Console.WriteLine(number);
number <<= 2;
Console.WriteLine(number);
number >>= 3;
Console.WriteLine(number);
}
}
}
Operators in C#
Casting and Type Conversions
1. Implicit conversions:
2. Explicit conversions (casts):
3. User-defined conversions:
4. Conversions with helper classes:
Operators in C#
Casting and Type Conversions
Implicit Conversions
Implicit Conversions
byte short, ushort, int, uint, long, ulong, float, double, or decimal
float double
class Test{
static void Main() {
double x = 1234.7;
int a;
a = (int)x; System.Console.WriteLine(a);
}
}
// Output: 1234
Operators in C#
Casting and Type Conversions
Explicit Numeric Conversions Table
From To
sbyte byte, ushort, uint, ulong, or char
byte Sbyte or char
float sbyte, byte, short, ushort, int, uint, long, ulong, char,or decimal
double sbyte, byte, short, ushort, int, uint, long, ulong, char, float,or decimal
Operators in C#
Casting and Type Conversions
User-defined conversions:
int result;
result = 5 + 3 * 9; // result = 32
Category Operators
Multiplicative *, /, %
Additive +, -
Equality ==, !=
Bitwise XOR ^
Bitwise OR |
Logical OR ||
Ternary ?:
Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
C# Keywords
Keywords are reserved words predefined to
the C# compiler.
These keywords cannot be used as
implici in (generic
foreach goto if in int
t modifier)
out (generic
null object operator out override params
modifier)
C# Keywords
Reserved Keywords
volatile while
C# Keywords
Contextual Keywords
descendi
add alias ascending dynamic from get
ng
partial
global group into join let orderby
(type)
partial
remov
(method select set
e
)
C# Keywords
Contextual Keywords
descendi
add alias ascending dynamic from get
ng
partial
global group into join let orderby
(type)
partial
remov
(method select set
e
)