C# fundamentals
What is C#?
• The new language in the .NET framework being implemented by
Microsoft. All .NET languages compile to a common byte code (MSIL)
making their integration into programs written in different languages
easier.
• Created by Microsoft
• Base on Java and C++.
• C# combines the best features of these languages and eradicates
some of their weaknesses
• C# programing language - more information
.NET Architecture
• CLR is the basic and Virtual Machine component of
the .NET Framework. It is the run-time environment in
the .NET Framework that runs the codes and helps in
making the development process easier by
providing the various services.
• Common Type System (CTS) describes the
datatypes that can be used by managed code. CTS
defines how these types are declared, used and
managed in the runtime.
• CLS stands for Common Language Specification and
it is a subset of CTS. It defines a set of rules and
restrictions that every language must follow which
runs under the .NET framework
Why choose C#?
• C# was designed from scratch with the .net in mind
• C# combines the power of C and C++ with the productivity of
Visual Basic
• C# is in sync with current web standards and is easily
integrated with existing applications.
• With its familiar syntax the transition for Java and C++
programmers will be an easy one
• One of the most popular programming language in the world
C#
• C# Can be used to develop two categories of programs:
• Executable application
• Component libraries
• Executable programs are written to carry out certain tasks and
require Main method.
• Component libraries do not require Main declaration because
they are not standalone application programs. (They are
written for use by other application)
Simple C# Program
Namespaces
System.Console.WriteLine() – Here System is a namespace in
which the Console class is located. The class can be accesed
using dot operator.C# supports using directive that can be used
to import the namespace Systeminto the program
Comments
• Enhances readability and understanding the code
• Program should have information such as implementation
details, change history.
• Types of comments:
• Single line comments (// )
• Multiline comments (/* …. …. … */)
Main returning a value
• Man can also returning a value if Main is declarated as int instead of
void
• When the return type is int, we must include a return statement at the
end of the method
Main returning a value - continue
• The value returned serves as the program termination status
code
• It allows communication of success of failure to the execution
enviroment.
Passing objects to method
Provide interactive input
Literals
• Literals are the value constans assigned to variables in the
porogram.
• C# Supports seven types of literals
• Integral literals: decimal and hexadecimals
• Real,
• Boolean (true, false)
• Single character
• Backslask character: ‘\a’, ‘\n’, ‘\r’
Variables
• Is an identifier that denotes storage location used to store data value
• Make take different values at different times during program execution
• Name should be meainingful
• May consist of alphabeths, digits and underscore
• Conditions
• Not begin with a digit
• Uppercase and lowercase are distinct
• It should be not a keyword
• White space not allowed
• Name can be of any length
Data types
• Every variable in c# is associated with a data type
• Specifies the size and type of values that can be stored
• Types in c#
• Value Types
• Reference types
• Value types are stored on stack
• Value is copied
• Reference types are stored on heap
• Only the reference is copied
Data types
Declaration of variables
• Declaration does three things
• Tells the compiler what the variable name is
• Specifies what type of data the variable gonna hold
• The place of declaration decides the scope of variable
Default Values
A variable is either explicity assigned a value or automatically
assigned a default value.
Constant values
• Variables whose valueas do not change during the program
execution are known as constants.
• Example
• const string Name = “Michal”
• const int Age = 34
• Advantages
• Program is easier to read
• Program is easier to modify
• Errors are minimized
Scope of variables
• It is region of code within the variable can be accesed
• Depends on type of the variable and its place of declaration
• Example
Scope of variables continue
• Static variables
• Declared at the class level
• Known as fields or fields variables
• The scope of this variables begins at the place of ther declaration
and end when the main method is terminates
• The value parameter x will exists tiil the end of “function” method
• The reference parameter y don’t create a news torage location
• Array element a[], come into existence when array instance is created
• Variable g is called local variable and their scope is until the end of
block inside which they are declared
Operators
• Arithmetic operators
• Relational operators
• Logical operators
• Increment and decrement
• Conditional operators
Arithmetic operators
Relational operators
• Relational operators are used to compare expressions
Logical operators
• Logical operators are used to combine two or more relational
expressions into a single expression
Increment and decrement
Incerement and decrement continue
• When used in prefix mode, incerement and decrement
operators modify their operand before it’s used.
• When used in postfix mode, incerement and decrement
operators modify their operand after it’s used.
Conditional operators
• Takes three operators
• Syntax: exp1 ? Exp2 : exp3;
Here if exp1 evaluated true then value of exp2 is assigned else
of exp3
• Example
int a = 10;
int b = 20;
int c = a > b ? a : b;
If statement
• Is a powerfull decision making statement
• Used to control the flow execution of statements
• General form
if (boolean-expression)
{
statement block
}
statement
If flowchart
If … else statement
• Extension of if statement
• General form
if (boolean-expression)
{
True block statement
}
else
{
False block statement
}
If… else flowchart
Nesting if…else statement
Switch statement
• If statement increases complexity of a program dramatically
as the alternatives increases
• The program becomes difficult to read and understand and
follow.
• C# offers an alternative with the help of switch statement
Switch statement example
While loop
• The process of repeatedly executing a block of statements is known as
looping
• Is an entry-controlled loop statement
• The test condition is evaluated and if the condition is true, then the
body of the loop is executed
• Syntax:
Initialization
While(test-condition)
{
body of the loop
}
While loop - example
Do… While loop
• On some occasions it might be necessary to execute the body of
the loop before test is performed
• This can be handled using do statement
• Is an exit-controlled loop statement
• The body of the loop is executed at least once
• Syntax:
Initialization;
do
{
body of the loop
} while(test-condition);
Do… While loop - example
For loop
• Is an entry-controlled loop
• Syntax:
for(initialization;testcondition;increment)
{
Body of the loop…..
}
• All the three actions, namely initialization, testing &
incrementing, are placed in the for statement itself
Methods
• Methods are declared inside the body of a class
• General form:
modifiers type methodname(parameters)
{
method---body
}
• Method declaration has a five parts
• Name of the method
• Type of value the method returns
• List of parameters
• Body of the method
• Method modifiers
Methods - example
Method modifiers
Invoking methods
• Once the method is defined, they must be activated for
operations
• Process of activating a method is known as invoking.
• General form
objectName.MethodName(parameters);
Method invoking - example
Static method invoking - example
Method parameters
• Value parameters
• Reference paramaters
• Output parameters
Value parameters
• By default method parameters are passed by value
• When a method is invoked, the value of actual parameters are
assigned to the corresponding formal parameters
• Any changes to formal parameters does not affect to actual
parameters
• There are two copies of variables when passed by value
Value parameters - example
Pass by reference
• We can force the value parameters to be passed by reference
• Use ref keyword
• It represent the same storage location as the actual
parameter
• When a formal parameter is declared as ref the corresponding
actual argument in the method invocation must be declared
as ref
• Use when we want to change the values of variables in the
calling method
Pass by reference example
Output parameters
• Used to pass results back to the calling method
• Declare the parameters with an out keyword
• It does not create a new storage location
• When a formal parameter is declared as a out, the
corresponding argument in the method invocation must also
be declared as out.
Output parameters - example
Arrays - introduction
• Array is a group of contiguous or related data items that share
a common name
• A particular value is indicated by writing a number called
index number or subscript in brackets after the array name
• Example :
marks[10]
• The complete set of values is referred to as an array
• The individual values are called elements
One dimension arrays
• Declaration of arrays
Example: int[] counter;
• Creation of arrays
Example: counter = new int[5];
• Combination
Example: int[] counter = new int[5];
• Initialization of arrays
Example: counter[0] = 10;
counter[1] = 2;
Int[] counter = {10, 2, 5};
Two dimension arrays
• Allow to store table of values
• Example: table[4,5];
• Each dimension form the array is indexed from zero to its maximum
size minus one
• Fiestr index specifies the row and second index specifies the column
within that row
• Declaration int[,] myArray;
• Creation: myArray = new int[3,4];
• Combination: int[,] myArray = new int[3,4];
• Initialization: int[,] n = { {0,0,0}, {1,1,1} };
System.Array Class
• In c# every array we create is automatically derived from
System.Array class.
Example
List
• Can store a dynamically sized array of objects.
• Has ability to grow dynamically
• Example:
List<string> cities = new List<string>();
Creates a list with a dynamic capacity
• Adding elements
cities.Add(“Warsaw”);
cities.Add(“Gdansk”);
• Removing
cities.Remove(“Warsaw”);
String introduction
• Represents a sequence of characters
• Example: string s1 = “abc1234”;
• Copying string: string s2 = s1; string s2 = string.Copy(s1);
• Concatenating string: string s3 = s1 + s2;
• Reading from keyboard: string s = Console.ReadLine();
• Conversion: int num = 123; string a = num.ToString();
• Verbatim strings.
String methods
• String object are immutable
• Thus we cannot modify the characters contained in them
• However we can produce a modified version of a string using
built in operations
• Methods: Compare(), Concat(), Copy(), Equals(), Insert(),
ToUpeer(), Join(), Replace(), Split(), ToLower(), ToUpper(),
Trim(), TrimStart(), TrimEnd()
Example
Mutable strings
• They can be modified using StringBuilder class
• Can grow dynamically
• Also known as dynamic strings
• Example:
StringBuilder s = new StringBuilder();
• Methods:
Append(), Insert(), Remove(), Replace()
• Property:
Capacity, Length, []
String builder - example
Regular expressions
• Provide a powerful tool for searching and manipulating a large text
• Used to:
• Locate substring
• Modify one of more substring
• Identify substrings that begin with begin or end with a pattern of
characters
• Find all words that begin with a group of characters and end with
some other characters
Regular expressions continue
• Regular expression is a string containing two types of
characters:
• Litrerals
• Metacharacters
• Literals are characters that we wish to search and match in
the text
• Metacharacters are special types of characters that give
commands to the regular expression parser
Regular expression example
OOP - Introduction
• C# is true object oriented language
• We create objects of a have class that have state and behavior.
• Object oriented language has 3 core principles:
• Encapsulation
• Inheritance
• Polymorphism
Member access modifiers
• OOP provides data hiding
• Class may be designed to hide its members from outside
visibility
• This is achived using access specifiers
• In c# all members have private access by default
Member access modifiers
• Private
Member is accessible only from the class containing the member
• Public
Member is accessible from anywhere outside the class as well. Also
accessible in derived class.
• Protected
Member is accessible only to its own class and in derived class.
• Internal
Member is available within the assembly or component that is being
created but not to the clients of that component.
Objects
• Object in c# is a block of memry that contains space to store
all the instance variable.
• Creating an object:
Rectangle rect = new Rectangle();
• We can create x number of objects of a class each having a
different memory storage area
• Accessing class members:
objectName.VariableName;
objectName.MethodName(parameters);
Constructors
• Used to initialize an object when it is create.
• Have the same name as class.
• They do not have return any value.
Constructors - example
Static members
• They are common to all the objects
• Are accesed without using a particular object
• Referred as class variables and class methods
• Static variable is common to all instances of the class
• Even methods can be declared as static
Static members example
Static constructors
• Is called before any object of a class is created
• Useful to do any housekeeping work that needs to be done once
• Used to assign initial values to status data members
• Static constructors do not have any parameters
• Example:
class Abc
{
static Abc()
{
…….
}
}
The “this” reference
• This refers to the object that called the method
• Used to distinguish between local and instance variables that have the same
name
• Example:
class Example
{
int x;
int y;
public void SetXY(int x, int y)
{
this.x = x;
this.y = y;
}
}
Constant members
• They are variables whose value cannot be change during
program execution
• Example:
public const int size = 20;
• Any attempt to change the value of a constant result in a
compilation error
• The const members are implicity static
• Const members are accesed using class name
• Value must be set when const is defined
Properties
• In c# private data members can be accesed only using
methods of a class
• Such method are called as an accessor methods
• C# provides “properties” that has same capabilities as of
accessor methods.
• Using property we can access data members as if they are
public
• Also referred to as a smart fields
Properties - example
Thank you!