Intro To C# - Part 1
Intro To C# - Part 1
Kitaw A.
Introduction
C# is a general-purpose, object-oriented, platform
independent programming language
Created by Anders Hejlsberg, a Danish Software Engineer who
works at Microsoft
The name "C sharp" was inspired by the musical notation where a
sharp indicates that the written note should be made a semitone
higher in pitch
Introduction
C# is General Purpose
You can develop varieties of applications using C#.
Windows desktop applications
Web applications
Web services
Mobile applications
Android
iOS
Windows Phone
Introduction
C# is object-oriented
C# is a rich implementation of the object-orientation paradigm,
which includes encapsulation, inheritance, and polymorphism
Encapsulation: Grouping of data and operations on data, and
protecting access from external objects
Inheritance: allows classes to inherit properties and behaviors of
another class
Polymorphism: allows the concept of “one interface, multiple
implementations”!
Introduction
In C#, classes contain mainly three members: attributes,
properties and methods
Attributes define what a class is; Methods describe actions
performed by a class and properties represent a piece of an
object’s state, such as a button’s color or a label’s text.
Introduction
C# is both statically typed, but supports dynamic typing
Static typing
Type checking at compile time
Dynamic typing
Type checking at run time
Introduction
A typical C# program consists of the following parts:
Namespace declaration
A class
Class methods, attributes, properties
A Main method
Statements and Expressions
Comments
Introduction
A “Hello World” example
using System;
namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
Introduction
C# is case sensitive
All statements and expression must end with a semicolon (;)
The program execution starts at the Main method
Unlike Java, program file name could be different from the class
name
Supports two types of comments
Single line //single like comment
Multi line /* multi line
comment */
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 should not be a C# keyword
Identifiers
Naming Conventions
There are currently two naming conventions in use in the .NET framework
namespaces, known as PascalCase and camelCase
The casing used in the names is indicative of their usage
They both apply to names that are made up of multiple words, and specify that each
word in a name should be in lower case except for its first letter, which should be
upper case
In camelCasing, there is an additional rule: that the first word should start with a
lower case letter
The following are camelCase variable names:
age
firstName
timeOfDeath
Identifiers
Naming Conventions
The following are PascalCase:
Age
CalculateSalary
WindowsFormsModule
PascalCase is used for naming properties, methods and classes
camelCase is used for naming variables and parameters.
Data types
There are two kinds of types in C#:
Value types and reference types
Variables of value types directly contain their data whereas
variables of reference types store references to their data
C#’s value types are integer, real, boolean, char
C#’s reference types are further divided into class types, interface
types, array types, and delegate types
Data types
Value Types
Signed integral: sbyte, short, int, long
Unsigned integral: byte, ushort, uint, ulong
Unicode characters: char
floating point: float, double
High-precision decimal: decimal
Boolean: bool
Data types
Value Types
Data types
Reference types
Class types
Ultimate base class of all other types: object
Unicode strings: string
User-defined types of the form class C {...}
Interface types
User-defined types of the form interface I {...}
Array types
Single- and multi-dimensional, for example, int[] and int[,]
Delegate types
User-defined types of the form delegate int D(...)
Data types
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
Introduced in C#.40
Adds dynamic typing in C#
Type conversion
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, 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
Type conversion
The Convert class ToSbyte
ToSingle
Converts base type to another base type
ToString
Provides a number of static methods to do so ToUInt16
ToBoolean
ToUInt32
ToByte
ToUInt64
ToChar
ToDateTime
ToDecimal
ToDouble
ToInt16
ToInt32
ToInt64
Variables
Variables in C# are created using the following syntax:
<datatype> <identifier> [= value];
Example:
int x;
dynamic d=“hello”;
d=7;
decimal f=1.3E10;
Operators
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
Miscellaneous Operators
Operators: arithmetic
A=10
B=20
Operators: relational
A=10
B=20
Operators: Logical
A=true
B=false
Operators: Bitwise
A= 0011 1100
B= 0000 1101
Operators: Miscellaneous
Decision making
Decision making structures requires the programmer to specify
one or more conditions to be evaluated or tested by the program,
along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements
to be executed if the condition is determined to be false
Decision making
C# provides following types of decision making statements.
if statement
if-else statement
if-else if-else statement
switch statement
It is always legal in C# to nest if-else statements, which means
you can use one if or else if statement inside another if or else if
statement(s)
Nesting also works for switch statements
Loops
There may be a situation, when you need to execute a block of code several number
of times
In general, the statements are executed sequentially: The first statement in a function
is executed first, followed by the second, and so on.
A loop statement allows us to execute a statement or a group of statements multiple
times
Loops
C# provides following types of loop to handle looping requirements
for loop
while loop
do-while loop
foreach loop
Exercises:
Simple BMI calculator
Quadratic solver
GCD finder
Read two integers, display how many times the second integer appears in the first
integer (e.g. 1 appears 2 times in 121)
Solutions for exercises
Simple BMI calculator
Using System;
class Program{
static void Main(string[] args){
double height,weight,bmi;
Console.WriteLine("Enter your height in meters: ");
height = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter your weight in kilograms: ");
weight = Convert.ToDouble(Console.ReadLine());
bmi = weight / (height * height);
if (bmi < 18.5)
Console.WriteLine("Underweight");
else if (bmi >= 18.5 && bmi < 24.9)
Console.WriteLine("Normal");
else
Console.WriteLine("Overweight“);
Console.ReadKey();
}
}
Solutions for exercises
Quadratic solver
Using System;
class Program{
static void Main(string[] args){
double a,b,c,determinant;
Console.WriteLine("Enter the value of a: ");
a = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter the value of b: ");
b = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter the value of c: ");
c = Convert.ToDouble(Console.ReadLine());
determinant = b * b – 4 * a * c;
if (determinant > 0){
determinant=Math.Sqrt(determinant);
double root1 = (-b + determinant)/(2*a);
double root2 = (-b - determinant)/(2*a);
Console.WriteLine(“Two roots: {0} and {1}”,root1,roo2);
}else if (determinant == 0){
determinant=Math.Sqrt(determinant);
double root = -b/(2*a);
Console.WriteLine(“One root: “+root);
}else
Console.WriteLine(“No root!“);
Console.ReadKey();
}
}
Solutions for exercises
GCD finder
Using System;
class Program{
static void Main(string[] args){
int a, b,gcd=1,min;
Console.WriteLine("Enter the first number: ");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the first number: ");
b = Convert.ToInt32(Console.ReadLine());
min = (a < b) ? a : b;
for(int i=1;i <= min,i++){
gcd = (a % i == 0 && b % i == 0)?i:gcd;
}
Console.WriteLine("GCD: "+gcd);
Console.ReadKey();
}
}
Solutions for exercises
Digit counter
Using System;
class Program{
static void Main(string[] args){
int a, b,c=0,n;
Console.WriteLine("Enter the first number: ");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the digit you want to count: ");
b = Convert.ToInt32(Console.ReadLine());
n = a;
while (n > 0){
if (b == n % 10)
c++;
n /= 10;
}
Console.WriteLine("{0} appears {1} times in {2}", b, c, a);
Console.ReadKey();
}
}