C# W23
C# W23
NET
The “Hello World” in C#
using System;
class Hello
{
static void Main(string[] args)
{
Console.WriteLine("Hello world!");
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("args[{0}] = {1}",
i, args[i]);
}
}
}
2
Main
Formy Main
3
Value Types
and Reference Types
int i = 123;
string s = "Text";
stack heap
i 123
s Text
4
Value type
• A variable of a value type contains an instance of the type
• Values are copied by default, on
• assignment
• passing an argument to a method
• returning a method result
• Struct
• Enum
• Tuple
• Might be generic
• All value types implicitly inherit from the class System.ValueType (seled
class)
• default constructor - parametrless instance constructor - returns a zero-
initialized instance (default value)
• Default constructor can be invoked
class Test
{
void F()
{
int i = 0;
int j = new int();
}}
Simple types
• Aliases for predefined struct types in the System namespace
Reference type
• String
• Arrays
• Class
• Delegate
• Default value
• null
Boxing
int i = 123;
object o = i;
stack heap
i 123
o System.Int32
123
The process of converting a value type to the type object or to any interface type
implemented by this value type 9
Object -> value type -> needs conversion
Boxing
• C#'s type system is unified, a value of any type can be treated as an
object
• Values of value types are treated as objects by performing boxing and
unboxing operations
C# Data Types
• object – reference to object
• string – sequence of Unicode characters
• byte, sbyte – 8-bit integer value
• short, ushort – 16-bit integer value
• int, uint – 32-bit integer value
• long, ulong – 64-bit integer value
• float, double – floating-point number
• bool – logical value (true or false)
• char – Unicode character
• decimal – fixed-point decimal number
11
Floating-point numeric types
• Float
• Range ±1.5 x 10−45 to ±3.4 x 1038
• Precision ~6 – 9 digits
• Double
• Range ±5.0 × 10−324 to ±1.7 × 10308
• Precision ~15-17 digits
• supported operators
• arithmetic
• comparison
• equality operators
double
• Double precision 64 bit number
• from negative 1.79769313486232e308 to positive 1.79769313486232e308
• positive or negative zero,
• PositiveInfinity,
• NegativeInfinity,
• not a number (NaN)
Part Bits
Significand or mantissa 0-51
Exponent 52-62
Sign (0 = Positive, 1 = Negative) 63
Floating point representation
double value = .1;
double result1 = value * 10;
double result2 = 0;
for (int i = 1; i <= 10; i++)
result2 += value;
// .1 * 10: 1
// .1 Added 10 times: 0.99999999999999989
Double.Epsilon
• Double.Epsilon - 4.94065645841247E-324 - the smallest positive Double value that is greater than zero
//tolerance
double difference = Math.Abs(double1 * .00001);
• Warning: acceptable margin of difference depends on the magnitude of the Double values
• Math.Round(Double, Int32) - also can be applied (rounds double to selected precision)
Floating point representation
• Floating-point numbers have a limited number of significant digits
• real value approximation
• Some floating-point operations may lack the precision to change a floating
point value
double v = 123456789012.34567;
double add = Double.Epsilon * 1e15; //4.94065645841247E-324 * 1e15
Console.WriteLine("{0} + {1} = {2}", value, additional,
value + additional);
//123456789012.346 + 4.94065645841247E-309 = 123456789012.346
Floating point special values
• Double.PositiveInfinity,
• Double.NegativeInfinity
• Double.PositiveInfinity,
• Double.NegativeInfinity,
• Double.NaN
Decimal
• Decimal
• decimal floating point number
• 128-bit data type
• has more precision and a smaller range than floating point types
• Range
• ±1.0 x 10-28 to ±7.9228 x 1028
• 79,228,162,514,264,337,593,543,950,335
• Precision
• 28-29 significant digits
19
Decimal
• Type does not eliminate the need for rounding.
• It minimizes errors due to rounding.
22
Arithmetic overflow and division by zero
• Integer arithmetic overflow
• Division by zero: DivideByZeroException
• Overflow: checked: OverflowException
• Floating-point arithmetic overflow
• Never throws exceptions
• Decimal
• Division by zero: DivideByZeroException
• Overflow: always: OverflowException
float / double behaviour
double a = 1.0 / 0.0; Console.WriteLine(a); // Infinity
Console.WriteLine(double.IsInfinity(a)); // True
Console.WriteLine(double.MaxValue + double.MaxValue); // Infinity
Console.WriteLine(double.IsNaN(b)); // True
Round off errors
Console.WriteLine(.41f % .2f); // output: 0.00999999
double a = 0.1;
double b = 3 * a;
Console.WriteLine(b == 0.3); // output: False
Console.WriteLine(b - 0.3); // output: 5.55111512312578E-17
decimal c = 1 / 3.0m;
decimal d = 3 * c;
Console.WriteLine(d == 1.0m); // output: False
Console.WriteLine(d); // output: 0.9999999999999999999999999999
System.Numerics
• Additional datatypes
BigInteger
• public struct BigInteger : IComparable,
IComparable<System.Numerics.BigInteger>,
IEquatable<System.Numerics.BigInteger>, IFormattable
• Properties
• Real (double)
• Imaginary (double)
• Properties are read only, all methods that performs actions return
new Complex number
Complex - constructor
//Call constructor
Complex c1 = new Complex(12, 6);
// From Double
Complex c2 = 3.14;
// Through cast
Complex c3 = (Complex) 12.3m;
• Equality
• CreateRotation
• GetDeterminant
Default values
• int i = default; // 0 pre C# 7.1 int i = default(int);
• float f = default;// 0
• decimal d = default;// 0
• bool b = default;// false
• char c = default;// '\0'
System.Math
• Constants
• Static methods for
• trigonometric
• logarithmic
• Other common mathematical functions
• Abs etc.
41
Implicit (automatical) numeric conversions
From To
byte short, ushort, int, uint, long, ulong, float, double, or decimal
float double
short ushort
int uint
double
decimal
43
Explicit numeric conversions
From To
sbyte byte, ushort, uint, ulong, or char
double sbyte, byte, short, ushort, int, uint, long, ulong, char, floa
t,or decimal
decimal sbyte, byte, short, ushort, int, uint, long, ulong, char, floa
t, or double
45
Value range
• // compile time error: Cannot implicitly convert type 'long' to 'int'.
• int i = 21474236473;
Value suffix
• uint ui = 120u;
• float fl = 11.2f;
• long l = 4533554522222l;
• ulong ul = 457554523333222ul;
• double d = 11452223.555d;
• decimal mon = 1320.15m;
Scientific notation
• double d = 0.32e2;
• Console.WriteLine(d); // 32;
• float f = 333.45e-2f;
• Console.WriteLine(f); // 3.3345
• decimal m = 5.2e6m;
• Console.WriteLine(m);// 5200000
Strings
• Series of characters
• Maximus size of a string in memory: 2GB
• Immutable
• Syste.String vs string
• no difference
char[] c = {'T','e','s','t'};
string s = @"multi \
line \
string";
Strings
string s1 = “Some text”;
string s2 = “c:\\temp\\myfile.dat”;
string s3 = @“c:\temp\myfile.dat”; // immediate
// string
// Length
int len = s1.Length;
// Concatenation
s1 = s1 + “ i psa”;
// Indexing
for (int i = 0; i < s1.Length; i++)
Console.WriteLine(„Znak {0} = {1}”, i, s1[i]);
51
Basic Strings Operations
string s1 = „Tekst”, s2 = „tekst”;
// Case-sensitive comparison
bool cmp1 = s1 == s2;
bool cmp2 = String.Compare(s1, s2) == 0;
// Case-insensitive comparison
bool cmp3 = String.Compare(s1, s2, true) == 0;
// Searching
int i1 = s1.IndexOf(“pattern”);
// Copying a substring
string substr = s1.Substring(2, 4);
// Replacing
s1 = s1.Replace(“old”, “new”);
52
String operations
String.IsNullOrEmpty(s1);
String.IsNullOrWhiteSpace(s1)
String.Split
String.Join
String.Contains
String.StartsWith
String.EndsWith
String.LastIndexOf
String.IndexOfAny
String.LastIndexOfAny
String.Equals
String operations
String.PadLeft / String.PadRight
String.Remove
String.ToLower
String.ToLowerInvariant
String.ToUpper
String.ToUpperInvariant
String interpolation (C# 6)
string name = “Test";
var date = DateTime.Now;
// Composite formatting:
Console.WriteLine("Hello, {0}! Day:{1}, current time:
{2:HH:mm}.", name, date.DayOfWeek, date);
// String interpolation:
Console.WriteLine($"Hello, {name}! Day: {date.DayOfWeek},
current time: {date:HH:mm}.");
{<interpolationExpression>[,<alignment>][:<formatString>]}
Console.WriteLine($"|{"Left",-7}|{"Right",7}|");
56
String interpolation (C# 6)
Brace, "{" or "}", in interpolated string,
use two braces, "{{" or "}}".
57
String Intern Pool
• Special table allocated on Large Object Heap
• Maintains all references to strings literals that are created by application
string string1 = "This is a string";
string string2 = "This is a string";
if((object)string1 == (object)string2)
Console.WriteLine("The references of string1 and string2 are equal");
else
Console.WriteLine("The references of string1 and string2 are unequal");
Console.ReadKey(true);
if((object)string1 == (object)string2)
Console.WriteLine("The references of string1 and string2 are equal");
else
Console.WriteLine("The references of string1 and string2 are unequal");
Console.ReadKey(true);
[assembly:CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)]
class Program
{
static void Main(string[] args)
{
Console.WriteLine("The CompilationRelaxationsAttribute activated.");
}
}
Operators
• Arithmetic: + - * / %
• Logical: & | ^ ! ~ && || true false
• String concatenation: +
• Incrementation and decrementation: ++ --
• Bitwise shift: << >>
• Comparisons: == != < > <= >=
• Assignments: = += -= *= /= %= &= |= ^= <<= >>=
• Member access and indexing: . []
• Type cast: () as
• Conditional operator: ?: ??
• Creating objects, type information: new is sizeof typeof
63
Checked Statement
static void Main(string[] args)
{
int x = Int32.MaxValue;
64
Checked statement
int a = int.MaxValue;
int b = 5;
// variables
int a = 12, b = 1;
int c;
//initialize only once
Public readonly double pi = 3.14
c = 2;
Console.WriteLine(a + b + c);
Console.WriteLine(pi * r * r);
}
68
const keyword vs readonly keyword
const
Cannot use static keyword (howevet they are accessed as
static field, the value is the same for all instances)
Are related to the whole class not single instace
Value is assigned during compilation
Value can be set only in declaration
Can be used in switch case
Only certain types can be const
Only build in types (excluding System.Object) can be const
string / dynamic / int …
ReadOnly
Can be proceeded with static keyword
Processed during runtime
Can be initialized at the level of declaration
as well as Constructor
69
Enumerations
enum Color
{
Red,
Green = 10,
Blue
}
70
Enumerations
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
Base type:
Integral based
enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
All references to the individual values of an enum are converted to numeric literals at
compile time
71
Enumerations
Conversion
72
Enumerations
FlagsAttribute
Indicates that an enumeration can be treated as a bit field; that is, a set of flags; not required
Helps IDE
[Flags]
public enum CarOptions
{
// The flag for SunRoof is 0001.
SunRoof = 0x01,
// The flag for Spoiler is 0010.
Spoiler = 0x02,
// The flag for FogLights is 0100.
FogLights = 0x04,
// The flag for TintedWindows is 1000.
TintedWindows = 0x08,
}
class FlagTest
{
static void Main()
{
// The bitwise OR of 0001 and 0100 is 0101.
CarOptions options = CarOptions.SunRoof | CarOptions.FogLights;
// Because the Flags attribute is specified, Console.WriteLine displays
// the name of each enum element that corresponds to a flag that has
// the value 1 in variable options.
Console.WriteLine(options);
// The integer value of 0101 is 5.
Console.WriteLine((int)options);
}
} 73
Enumerations – get underlying type
• Enumeration type
74
Enumerations
• Enum to string
var text = Suit.Clubs.ToString(); // "Clubs"
var text2 = Enum.GetName(typeof(Suit), Suit.Clubs); // "Clubs"
var text3 = typeof(Suit).GetEnumName(Suit.Clubs); // "Clubs„
• String to Enum
Suit suit3;
var success = Enum.TryParse("NotASuit", out suit3); // false
75
Enumerations
• Get values - Array
76
Enumerations – Extension methods
• Can’t add custom methods to an enum type directly
• Solution:
• Extension methods
public static Color GetColor(this Suit @this)
{
switch (@this)
{
case Suit.Spades:
case Suit.Clubs:
return Color.Black;
case Suit.Diamonds:
case Suit.Hearts:
return Color.Red;
default:
throw new ArgumentException("Unexpected suit " + @this, "this");
}
}
77
var color = Suit.Hearts.GetColor(); // Color.Red
Enumerations
• A variable of an enum value can hold any value of the underlying type, not just one of the
named values
• Type-Safe: NO
78
Enumerations – custom attributes
[Flags]
enum BookFlags
{
...
[Description("Hard cover")]
HardCover = 1
...
}
79
Enumeration - Alias
80
Enumeration –operators
+
Enum + literal / variable of enum underlying type
++
--
Returns enum
-
enum-enum
return number
Bitwise
^, &, |, ~ 81