SlideShare a Scribd company logo
1 of 30
C# - Introduction
Language Fundamentals:
Data Types
string
Objects and Classes
Methods
Iteration and Selection
Arrays
C#
• All program logic must be embedded in (typically) a class.
Like Java.
• Every executable program must contain a Main-method.
The Main-method is the starting point of the application.
• The Main-method has several overloads:
– static int Main(string[] args), static void Main(string[] args),
static void Main() or static int Main()
• C# is case-sensitive
• C# supports operator and method overloading
• No multiple enhiritance (only interfaces – as in Java)
• All classes inherit object – as in Java
• Garbage-collection
C#
- data types
Keyword Description Special format for literals
bool Boolean true false
char 16 bit Unicode character 'A' 'x0041' 'u0041'
sbyte 8 bit signed integer none
byte 8 bit unsigned integer none
short 16 bit signed integer none
ushort 16 bit unsigned integer none
int 32 bit signed integer none
uint 32 bit unsigned integer U suffix
long 64 bit signed integer L or l suffix
ulong 64 bit unsigned integer U/u and L/l suffix
float 32 bit floating point F or f suffix
double 64 bit floating point no suffix
decimal 128 bit high precision M or m suffix
string character sequence "hello", @"C:dirfile.txt"
C#
- the string data type
• string is an alias for System.String – so
string is a class
• Many useful properties and methods are
offered by string:
– Length (property)
– Concat()
– CompareTo()
– Etc.
C#
- using types in C#
• Declaration before use (compiler checked)
• Initialisation before use (compiler checked)
public class App
{
public static void Main()
{
int width, height;
width = 2;
height = 4;
int area = width * height;
int x;
int y = x * 2;
...
}
}
declarations
declaration + initialization
error, x is not initialised
Arithmetics I
• C# offers the usual arithmetic operations: +, -, * , /
and % (modulus)
• +, - and * are defined as usual
• / is overloaded:
– If the operand are integers, the integer division is
applied:
• 23 / 4 gives 5
– If one of the operands is a floating point, the result also
is a floating point:
• 23.0 / 4 gives 5.75
– typecasting may be necessary
Arithmetics II
• The modulus operator yields the remainder with integer
division:
– 23 % 4 gives 3, because 23 divide by 4 yields the quotient 5 and
the remainder 3
• The usual rules of operator precedence are valid in C#:
– 2 + 3 * 4 = 2 + (3 * 4) = 14
– (2+3) * 4 = 20
Arithmetics and Data Types
• In C# the result of an arithmetic operation has the
“larger” type of the two operands:
– int + long yields a long
– float + double yields a double
– byte + float yields a float
– etc.
• It is always possible to assign a variable of a
“larger” type a value of a “smaller” type
– int x = 23;
– long y = x;
Type Casting
• One can change the type of an expression using explicit
casting:
int count = 24;
int total = 100;
float average = (float) total / count ;
• Syntax: (data type) variable name
• Type casting has higher precedence than arithmetic
operations
C#
- type conversion
• Some type conversions are done automatically
– from “smaller” to “larger” type
• Otherwise explicit casting og conversion must be applied:
– Type cast: prefix the type name in parentheses
– Conversion: use the System.Convert-class
int i = 5;
double d = 3.2;
string s = "496";
d = i;
i = (int) d;
i = System.Convert.ToInt32(s);
implicit cast
Explicit cast is needed
Conversion
C#
- Namespaces and Using
• Namespaces is a tool for structuring programs and systems
• Makes it possible to use the same names (identifiers) in
different parts of an application.
• Namespaces may be nested
• Visual Studio creates default a namespace with the same
name as the project
• using <namespace name> tells the compiler where to look
for definitions that our program refers to
• Namespaces are not the same as Java-packages, but they
are used for the same things and there are similarities
C#
- constructors
• Are called when an object is created:
– HelloClass h = new HelloClass("Carl");
– This constructor takes a parameter of type string
• The constructor’s job is to initialise the object, that is to
assign valid values to the instance variables of the object
• A default-constructor is created automatically:
– The default-constructor takes no arguments and initialises the
instance variables to their default values
– The default-constructor may be overridden be writing a
constructor with no parameters
C#
- value- and reference-types
• Objects of value-type are stack allocated – objects
of reference type are allocated on the heap
• Value types dies, when control goes out of the
scope, where they are declared – reference types
removed by the garbage collector
• Value types are copied with assignment – with
reference types a reference (the address) is copied
C#
- reference types - example
• creation, assignment and comparison:
Customer c1, c2, c3;
string s1, s2;
c1 = new Customer("Flemming Sander", 36259);
c2 = new Customer(”Bjarne Riis", 55298);
c3 = null; // c3 refers to nothing
c3 = c1; // c3 refers to the same object as c1
if (c1 == null) ... // is c1 referring to something?
if (c1 == c2) ... // compare references
if (c1.Equals(c2)) ... // compares object-values
C#
- When are objects equal?
• Classes ought to override the Equals-method
public class Customer
{
.
.
.
public override bool Equals(object obj)
{
Customer other;
if ((obj == null) || (!(obj is Customer)))
return false; // surely not equal
other = (Customer) obj; // explicit typecast
return this.id == other.id; // equal if ids are...
}
}
C#
- Boxing and Unboxing
• C# converts automatically between simple value and
object
– value => object = "boxing“ (the value is “wrapped in a box”)
– object => value = "unboxing“ (the value is unwrapped again)
int i, j;
object obj;
string s;
i = 32;
obj = i; // boxing (copy)
i = 19;
j = (int) obj; // unboxing!
s = j.ToString(); // boxing!
s = 99.ToString(); // boxing!
C#
- arrays
• Arrays are reference types
– Created from the Array-class in FCL
– Created using the new-operator
– 0-based indexing
– Are initialised with default value (0 if numeric, null if reference)
int[] a;
a = new int[5];
a[0] = 17;
a[1] = 32;
int x = a[0] + a[1] + a[4];
int l = a.Length;
Access element 1
Creation
Number of elements
C#
- enumerations
• Originally a C/C++ construction used to assigning
symbolic names to numerical values:
enum Month {
January= 1, February = 2,…,December = 12
}
public static void GetSeason(Month m)
{
switch(m)
{
case Month.January:
Console.WriteLine(”Winter”);
……
C#
- structs
• In some ways like a class, but there are
differences:
– Can have instance variables and methods
– Cannot have a default constructor
– Variables of a struct-type are value types and as such
stack allocated
– Can only inherit from interfaces
– Cannot be inherited from
• Can be used to implement ADTs, but no
inheritance and polymorphism
Decision Constructs
• To control the flow of program execution, C# defines two
simple constructs to alter the flow of your program
– The if/else statement
– The switch statement
• Like Java
C#
- selection and iteration
x = obj.foo();
if (x > 0 && x < 10)
count++;
else if (x == -1)
...
else {
...
}
while (x > 0)
{
...
x--;
} for (int k = 0; k < 10; k++)
{
...
}
C#
- foreach-loop
• foreach loop is used to sweep over collections
as arrays
– Reduces the risk of indexing errors
int[] data = { 1, 2, 3, 4, 5 };
int sum = 0;
foreach (int x in data)
{
sum += x;
}
foreach
type value collection
Method Parameter Modifiers
• C# provides a set of parameter modifiers that control how
arguments are sent into (and possibly returned from) a
given method.
The Default Parameter-Passing
// Arguments are passed by value by default.
public static int Add(int x, int y)
{
int ans = x + y;
// Caller will not see these changes
// as you are modifying a copy of the
// original data.
x = 10000;
y = 88888;
return ans;
}
The out Modifier
// Output parameters are allocated by the member.
public static void Add(int x, int y, out int ans)
{
ans = x + y;
}
static void Main(string[] args)
{
// No need to assign local output variables.
int ans;
Add(90, 90, out ans);
Console.WriteLine("90 + 90 = {0} ", ans);
}
The ref Modifier
public static void SwapStrings(ref string s1,
ref string s2)
{
string tempStr = s1;
s1 = s2;
s2 = tempStr;
}
static void Main(string[] args)
{
string s = "First string";
string s2 = "My other string";
Console.WriteLine("Before: {0}, {1} ", s, s2);
SwapStrings(ref s, ref s2);
Console.WriteLine("After: {0}, {1} ", s, s2);
}
The params Modifier
// Return average of 'some number' of doubles.
static double CalculateAverage(params double[] values)
{
double sum = 0;
for (int i = 0; i < values.Length; i++)
sum += values[i];
return (sum / values.Length);
}
static void Main(string[] args)
{
// Pass in a comma-delimited list of doubles...
double average;
average = CalculateAverage(4.0, 3.2, 5.7);
Console.WriteLine("Average of 4.0, 3.2, 5.7 is: {0}",
average);
// ...or pass an array of doubles.
double[] data = { 4.0, 3.2, 5.7 };
average = CalculateAverage(data);
Console.WriteLine("Average of data is: {0}", average);
}
C#
- Methods
• A class may have two kind of methods:
– Instance methods
– Static methods (class methods)
– Instance methods need an object to be invoked
– Static methods are called using the class name
only
C#
- Example
• The array-class in BCL (FCL)
– The class is a member of namespace System (System.Array)
namespace System
{
public class Array
{
public int GetLength(int dimension)
{ ... }
public static void Sort(Array a)
{ ... }
.
.
.
}
}
instance method
static method
C#
- calling the methods
/* main.cs */
using System;
public class App
{
public static void Main()
{
int[] data = { 11, 7, 38, 55, 3 };
Array.Sort(data);
for (int i=0; i<data.GetLength(0); i++)
Console.WriteLine(i + ": " + data[i]);
}
}
Class-method
Instance-method

More Related Content

What's hot (20)

constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++
 
OOP
OOPOOP
OOP
 
C++
C++C++
C++
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
C++11
C++11C++11
C++11
 
Dr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot netDr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot net
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5
 
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
 
C++11
C++11C++11
C++11
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 

Similar to Introduction to C#

C# 7 development
C# 7 developmentC# 7 development
C# 7 developmentFisnik Doko
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp PresentationVishwa Mohan
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerAndrey Karpov
 
Bringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptxBringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptxMaarten Balliauw
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginnersophoeutsen2
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#Hawkman Academy
 
Dr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr-archana-dhawan-bajaj
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants Hemantha Kulathilake
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overviewTAlha MAlik
 
C++ programming intro
C++ programming introC++ programming intro
C++ programming intromarklaloo
 

Similar to Introduction to C# (20)

C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
Aspdot
AspdotAspdot
Aspdot
 
Bringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptxBringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptx
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginner
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Dr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slides
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants
 
Return of c++
Return of c++Return of c++
Return of c++
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
C++ programming intro
C++ programming introC++ programming intro
C++ programming intro
 

More from ANURAG SINGH

Microsoft Azure Cloud fundamentals
Microsoft Azure Cloud fundamentalsMicrosoft Azure Cloud fundamentals
Microsoft Azure Cloud fundamentalsANURAG SINGH
 
Design thinkinga primer
Design thinkinga primerDesign thinkinga primer
Design thinkinga primerANURAG SINGH
 
Procurement Workflow in terms of SAP Tables Changes
Procurement Workflow in terms of SAP Tables ChangesProcurement Workflow in terms of SAP Tables Changes
Procurement Workflow in terms of SAP Tables ChangesANURAG SINGH
 
Intro to data science
Intro to data scienceIntro to data science
Intro to data scienceANURAG SINGH
 
Unit testing Behaviour Driven Development
Unit testing Behaviour Driven DevelopmentUnit testing Behaviour Driven Development
Unit testing Behaviour Driven DevelopmentANURAG SINGH
 
Introduction To Data Science Using R
Introduction To Data Science Using RIntroduction To Data Science Using R
Introduction To Data Science Using RANURAG SINGH
 
Intro todatascience casestudyapproach
Intro todatascience casestudyapproachIntro todatascience casestudyapproach
Intro todatascience casestudyapproachANURAG SINGH
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#ANURAG SINGH
 
Introduction to ,NET Framework
Introduction to ,NET FrameworkIntroduction to ,NET Framework
Introduction to ,NET FrameworkANURAG SINGH
 

More from ANURAG SINGH (9)

Microsoft Azure Cloud fundamentals
Microsoft Azure Cloud fundamentalsMicrosoft Azure Cloud fundamentals
Microsoft Azure Cloud fundamentals
 
Design thinkinga primer
Design thinkinga primerDesign thinkinga primer
Design thinkinga primer
 
Procurement Workflow in terms of SAP Tables Changes
Procurement Workflow in terms of SAP Tables ChangesProcurement Workflow in terms of SAP Tables Changes
Procurement Workflow in terms of SAP Tables Changes
 
Intro to data science
Intro to data scienceIntro to data science
Intro to data science
 
Unit testing Behaviour Driven Development
Unit testing Behaviour Driven DevelopmentUnit testing Behaviour Driven Development
Unit testing Behaviour Driven Development
 
Introduction To Data Science Using R
Introduction To Data Science Using RIntroduction To Data Science Using R
Introduction To Data Science Using R
 
Intro todatascience casestudyapproach
Intro todatascience casestudyapproachIntro todatascience casestudyapproach
Intro todatascience casestudyapproach
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#
 
Introduction to ,NET Framework
Introduction to ,NET FrameworkIntroduction to ,NET Framework
Introduction to ,NET Framework
 

Recently uploaded

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 

Recently uploaded (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

Introduction to C#

  • 1. C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection Arrays
  • 2. C# • All program logic must be embedded in (typically) a class. Like Java. • Every executable program must contain a Main-method. The Main-method is the starting point of the application. • The Main-method has several overloads: – static int Main(string[] args), static void Main(string[] args), static void Main() or static int Main() • C# is case-sensitive • C# supports operator and method overloading • No multiple enhiritance (only interfaces – as in Java) • All classes inherit object – as in Java • Garbage-collection
  • 3. C# - data types Keyword Description Special format for literals bool Boolean true false char 16 bit Unicode character 'A' 'x0041' 'u0041' sbyte 8 bit signed integer none byte 8 bit unsigned integer none short 16 bit signed integer none ushort 16 bit unsigned integer none int 32 bit signed integer none uint 32 bit unsigned integer U suffix long 64 bit signed integer L or l suffix ulong 64 bit unsigned integer U/u and L/l suffix float 32 bit floating point F or f suffix double 64 bit floating point no suffix decimal 128 bit high precision M or m suffix string character sequence "hello", @"C:dirfile.txt"
  • 4. C# - the string data type • string is an alias for System.String – so string is a class • Many useful properties and methods are offered by string: – Length (property) – Concat() – CompareTo() – Etc.
  • 5. C# - using types in C# • Declaration before use (compiler checked) • Initialisation before use (compiler checked) public class App { public static void Main() { int width, height; width = 2; height = 4; int area = width * height; int x; int y = x * 2; ... } } declarations declaration + initialization error, x is not initialised
  • 6. Arithmetics I • C# offers the usual arithmetic operations: +, -, * , / and % (modulus) • +, - and * are defined as usual • / is overloaded: – If the operand are integers, the integer division is applied: • 23 / 4 gives 5 – If one of the operands is a floating point, the result also is a floating point: • 23.0 / 4 gives 5.75 – typecasting may be necessary
  • 7. Arithmetics II • The modulus operator yields the remainder with integer division: – 23 % 4 gives 3, because 23 divide by 4 yields the quotient 5 and the remainder 3 • The usual rules of operator precedence are valid in C#: – 2 + 3 * 4 = 2 + (3 * 4) = 14 – (2+3) * 4 = 20
  • 8. Arithmetics and Data Types • In C# the result of an arithmetic operation has the “larger” type of the two operands: – int + long yields a long – float + double yields a double – byte + float yields a float – etc. • It is always possible to assign a variable of a “larger” type a value of a “smaller” type – int x = 23; – long y = x;
  • 9. Type Casting • One can change the type of an expression using explicit casting: int count = 24; int total = 100; float average = (float) total / count ; • Syntax: (data type) variable name • Type casting has higher precedence than arithmetic operations
  • 10. C# - type conversion • Some type conversions are done automatically – from “smaller” to “larger” type • Otherwise explicit casting og conversion must be applied: – Type cast: prefix the type name in parentheses – Conversion: use the System.Convert-class int i = 5; double d = 3.2; string s = "496"; d = i; i = (int) d; i = System.Convert.ToInt32(s); implicit cast Explicit cast is needed Conversion
  • 11. C# - Namespaces and Using • Namespaces is a tool for structuring programs and systems • Makes it possible to use the same names (identifiers) in different parts of an application. • Namespaces may be nested • Visual Studio creates default a namespace with the same name as the project • using <namespace name> tells the compiler where to look for definitions that our program refers to • Namespaces are not the same as Java-packages, but they are used for the same things and there are similarities
  • 12. C# - constructors • Are called when an object is created: – HelloClass h = new HelloClass("Carl"); – This constructor takes a parameter of type string • The constructor’s job is to initialise the object, that is to assign valid values to the instance variables of the object • A default-constructor is created automatically: – The default-constructor takes no arguments and initialises the instance variables to their default values – The default-constructor may be overridden be writing a constructor with no parameters
  • 13. C# - value- and reference-types • Objects of value-type are stack allocated – objects of reference type are allocated on the heap • Value types dies, when control goes out of the scope, where they are declared – reference types removed by the garbage collector • Value types are copied with assignment – with reference types a reference (the address) is copied
  • 14. C# - reference types - example • creation, assignment and comparison: Customer c1, c2, c3; string s1, s2; c1 = new Customer("Flemming Sander", 36259); c2 = new Customer(”Bjarne Riis", 55298); c3 = null; // c3 refers to nothing c3 = c1; // c3 refers to the same object as c1 if (c1 == null) ... // is c1 referring to something? if (c1 == c2) ... // compare references if (c1.Equals(c2)) ... // compares object-values
  • 15. C# - When are objects equal? • Classes ought to override the Equals-method public class Customer { . . . public override bool Equals(object obj) { Customer other; if ((obj == null) || (!(obj is Customer))) return false; // surely not equal other = (Customer) obj; // explicit typecast return this.id == other.id; // equal if ids are... } }
  • 16. C# - Boxing and Unboxing • C# converts automatically between simple value and object – value => object = "boxing“ (the value is “wrapped in a box”) – object => value = "unboxing“ (the value is unwrapped again) int i, j; object obj; string s; i = 32; obj = i; // boxing (copy) i = 19; j = (int) obj; // unboxing! s = j.ToString(); // boxing! s = 99.ToString(); // boxing!
  • 17. C# - arrays • Arrays are reference types – Created from the Array-class in FCL – Created using the new-operator – 0-based indexing – Are initialised with default value (0 if numeric, null if reference) int[] a; a = new int[5]; a[0] = 17; a[1] = 32; int x = a[0] + a[1] + a[4]; int l = a.Length; Access element 1 Creation Number of elements
  • 18. C# - enumerations • Originally a C/C++ construction used to assigning symbolic names to numerical values: enum Month { January= 1, February = 2,…,December = 12 } public static void GetSeason(Month m) { switch(m) { case Month.January: Console.WriteLine(”Winter”); ……
  • 19. C# - structs • In some ways like a class, but there are differences: – Can have instance variables and methods – Cannot have a default constructor – Variables of a struct-type are value types and as such stack allocated – Can only inherit from interfaces – Cannot be inherited from • Can be used to implement ADTs, but no inheritance and polymorphism
  • 20. Decision Constructs • To control the flow of program execution, C# defines two simple constructs to alter the flow of your program – The if/else statement – The switch statement • Like Java
  • 21. C# - selection and iteration x = obj.foo(); if (x > 0 && x < 10) count++; else if (x == -1) ... else { ... } while (x > 0) { ... x--; } for (int k = 0; k < 10; k++) { ... }
  • 22. C# - foreach-loop • foreach loop is used to sweep over collections as arrays – Reduces the risk of indexing errors int[] data = { 1, 2, 3, 4, 5 }; int sum = 0; foreach (int x in data) { sum += x; } foreach type value collection
  • 23. Method Parameter Modifiers • C# provides a set of parameter modifiers that control how arguments are sent into (and possibly returned from) a given method.
  • 24. The Default Parameter-Passing // Arguments are passed by value by default. public static int Add(int x, int y) { int ans = x + y; // Caller will not see these changes // as you are modifying a copy of the // original data. x = 10000; y = 88888; return ans; }
  • 25. The out Modifier // Output parameters are allocated by the member. public static void Add(int x, int y, out int ans) { ans = x + y; } static void Main(string[] args) { // No need to assign local output variables. int ans; Add(90, 90, out ans); Console.WriteLine("90 + 90 = {0} ", ans); }
  • 26. The ref Modifier public static void SwapStrings(ref string s1, ref string s2) { string tempStr = s1; s1 = s2; s2 = tempStr; } static void Main(string[] args) { string s = "First string"; string s2 = "My other string"; Console.WriteLine("Before: {0}, {1} ", s, s2); SwapStrings(ref s, ref s2); Console.WriteLine("After: {0}, {1} ", s, s2); }
  • 27. The params Modifier // Return average of 'some number' of doubles. static double CalculateAverage(params double[] values) { double sum = 0; for (int i = 0; i < values.Length; i++) sum += values[i]; return (sum / values.Length); } static void Main(string[] args) { // Pass in a comma-delimited list of doubles... double average; average = CalculateAverage(4.0, 3.2, 5.7); Console.WriteLine("Average of 4.0, 3.2, 5.7 is: {0}", average); // ...or pass an array of doubles. double[] data = { 4.0, 3.2, 5.7 }; average = CalculateAverage(data); Console.WriteLine("Average of data is: {0}", average); }
  • 28. C# - Methods • A class may have two kind of methods: – Instance methods – Static methods (class methods) – Instance methods need an object to be invoked – Static methods are called using the class name only
  • 29. C# - Example • The array-class in BCL (FCL) – The class is a member of namespace System (System.Array) namespace System { public class Array { public int GetLength(int dimension) { ... } public static void Sort(Array a) { ... } . . . } } instance method static method
  • 30. C# - calling the methods /* main.cs */ using System; public class App { public static void Main() { int[] data = { 11, 7, 38, 55, 3 }; Array.Sort(data); for (int i=0; i<data.GetLength(0); i++) Console.WriteLine(i + ": " + data[i]); } } Class-method Instance-method