SlideShare una empresa de Scribd logo
1 de 92
Descargar para leer sin conexión
Mohammad Shaker
mohammadshaker.com
C# Programming Course
@ZGTRShaker
2011, 2012, 2013, 2014
C# Starter
L03 – Utilities
Today’s Agenda
• const and readonly
• Casting
– Direct Casting
– as Keyword
• is Keyword
• enums
• Exception Handling
• UnSafe Code
• Nullable Types
• using Keyword
• Files
• Class Diagram
• Windows Forms
const and readonly
const and readonly
• const
– Must be initialized in the time of declaration
• readonly
– keyword is a modifier that you can use on fields. When a field declaration includes
a readonly modifier, assignments to the fields introduced by the declaration can only occur as
part of the declaration or in a constructor in the same class.
public const int WEIGHT = 1000;
public readonly int y = 5;
const and readonly
• const
– Must be initialized in the time of declaration
• readonly
– keyword is a modifier that you can use on fields. When a field declaration includes
a readonly modifier, assignments to the fields introduced by the declaration can only occur as
part of the declaration or in a constructor in the same class.
public const int WEIGHT = 1000;
public readonly int y = 5;
public readonly int y = 5;
public readonly int y;
const and readonly
• const
– Must be initialized in the time of declaration
• readonly
– keyword is a modifier that you can use on fields. When a field declaration includes
a readonly modifier, assignments to the fields introduced by the declaration can only occur as
part of the declaration or in a constructor in the same class.
public const int WEIGHT = 1000;
public readonly int y = 5;
public readonly int y = 5;
public readonly int y;
Casting
Casting
Direct Casting “as” Keyword
void Example(object o)
{
// Casting
string s = (string)o; // 1 (Direct Casting)
// -OR-
string s = o as string; // 2 (Casting with “as” Keyword)
// -OR-
string s = o.ToString(); // 3 Calling a method
}
Casting
• What’s the difference? Output?
void Example(object o)
{
// Casting
string s = (string)o; // 1 (Direct Casting)
// -OR-
string s = o as string; // 2 (Casting with “as” Keyword)
// -OR-
string s = o.ToString(); // 3 Calling a method
}
Casting
• What’s the difference? Output?
Number (“1”)
• If (o is not a string) Throws InvalidCastException if o is not a string.
• Otherwise, assigns o to s, even if o is null.
void Example(object o)
{
// Casting
string s = (string)o; // 1 (Direct Casting)
// -OR-
string s = o as string; // 2 (Casting with “as” Keyword)
// -OR-
string s = o.ToString(); // 3 Calling a method
}
Casting
• What’s the difference? Output?
Number (“2”)
• Assigns null to s if o is not a string or if o is null.
• Otherwise assign to s “CAN’T BE A NULL VALUE”
For this reason, you cannot use it with value types.
void Example(object o)
{
// Casting
string s = (string)o; // 1 (Direct Casting)
// -OR-
string s = o as string; // 2 (Casting with “as” Keyword)
// -OR-
string s = o.ToString(); // 3 Calling a method
}
Casting
• What’s the difference? Output?
Number(“3”)
• Causes a NullReferenceException of o is null.
• Assigns whatever o.ToString() returns to s, no matter what type o is.
void Example(object o)
{
// Casting
string s = (string)o; // 1 (Direct Casting)
// -OR-
string s = o as string; // 2 (Casting with “as” Keyword)
// -OR-
string s = o.ToString(); // 3 Calling a method
}
Casting
• What’s the difference? Output?
1. Throws InvalidCastException if o is not a string. Otherwise, assigns o to s, even if o is null.
2. Assigns null to s if o is not a string or if o is null. Otherwise, assigns o to s. For this reason, you cannot use it with
value types.
3. Causes a NullReferenceException of o is null. Assigns whatever o.ToString() returns to s, no matter what type o is.
void Example(object o)
{
// I swear o is a string, C# compiler! I’m ordering you to cast, I know what am doing!
string s = (string)o; // 1 (Direct Casting)
// I Donna know whether o is a string or not, try a cast and tell me!
string s = o as string; // 2 (Casting with “as” Keyword)
// Am programming badly with this code!
string s = o.ToString(); // 3 Calling a method
}
Casting
• Meaning!
void Example(object o)
{
// I swear o is a string, C# compiler! I’m ordering you to cast, I know what am doing!
string s = (string)o; // 1 (Direct Casting)
// I Donna know whether o is a string or not, try a cast and tell me!
string s = o as string; // 2 (Casting with “as” Keyword)
// Am programming badly with this code!
string s = o.ToString(); // 3 Calling a method
}
Casting
• Meaning!
“as” casting will never throw an exception, while “Direct cast” can.
void Example(object o)
{
// I swear o is a string, C# compiler! I’m ordering you to cast, I know what am doing!
string s = (string)o; // 1 (Direct Casting)
// I Donna know whether o is a string or not, try a cast and tell me!
string s = o as string; // 2 (Casting with “as” Keyword)
// Am programming badly with this code!
string s = o.ToString(); // 3 Calling a method
}
Casting
• Meaning!
“as” casting will never throw an exception, while “Direct cast” can.
“as” cannot be used with value types (non-nullable types).
using System;
class MyClass1{}
class MyClass2{}
public class IsTest
{
public static void Main()
{
object[] myObjects = new object[6];
myObjects[0] = new MyClass1();
myObjects[1] = new MyClass2();
myObjects[2] = "hello";
myObjects[3] = 123;
myObjects[4] = 123.4;
myObjects[5] = null;
for (int i = 0; i < myObjects.Length; ++i)
{
string s = myObjects[i] as string;
Console.Write("{0}:", i);
if (s!= null)
Console.WriteLine("'" + s + "'");
else
Console.WriteLine("not a string");
}
}
}
Casting
using System;
class MyClass1{}
class MyClass2{}
public class IsTest
{
public static void Main()
{
object[] myObjects = new object[6];
myObjects[0] = new MyClass1();
myObjects[1] = new MyClass2();
myObjects[2] = "hello";
myObjects[3] = 123;
myObjects[4] = 123.4;
myObjects[5] = null;
for (int i = 0; i < myObjects.Length; ++i)
{
string s = myObjects[i] as string;
Console.Write("{0}:", i);
if (s!= null)
Console.WriteLine("'" + s + "'");
else
Console.WriteLine("not a string");
}
}
}
Casting
0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string
is Keyword
“is” Keyword
• The is operator is used to check whether the run-time type of an object is
compatible with a given type.
• The is operator is used in an expression of the form:
expression is type
“is” Keyword
• Let’s have the following example
class Class1{}
class Class2{}
“is” Keyword
public class IsTest
{
public static void Test(object o)
{
Class1 a;
Class2 b;
if (o is Class1)
{
Console.WriteLine("o is Class1");
a = (Class1)o;
// do something with a
}
else if (o is Class2)
{
Console.WriteLine("o is Class2");
b = (Class2)o;
// do something with b
}
else
{
Console.WriteLine("o is neither Class1 nor Class2.");
}
}
public static void Main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
Test(c1);
Test(c2);
Test("a string");
}
}
“is” Keyword
public class IsTest
{
public static void Test(object o)
{
Class1 a;
Class2 b;
if (o is Class1)
{
Console.WriteLine("o is Class1");
a = (Class1)o;
// do something with a
}
else if (o is Class2)
{
Console.WriteLine("o is Class2");
b = (Class2)o;
// do something with b
}
else
{
Console.WriteLine("o is neither Class1 nor Class2.");
}
}
public static void Main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
Test(c1);
Test(c2);
Test("a string");
}
}
o is Class1
o is Class2
o is neither Class1 nor Class2.
Press any key to continue...
enum
enum
• As easy as:
• And that’s it!
// You define enumerations outside of other classes.
public enum DaysOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
DaysOfWeek dayOfWeek = DaysOfWeek.Monday;
if(dayOfWeek == Wednesday)
{
// Do something here
}
Exception Handling
Exception Hierarchy
Exception Handling
using System;
using System.IO;
class tryCatchDemo
{
static void Main(string[] args)
{
try
{
File.OpenRead("NonExistentFile");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
The output?
Exception Handling
using System;
using System.IO;
class tryCatchDemo
{
static void Main(string[] args)
{
try
{
File.OpenRead("NonExistentFile");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
The output?
Exception Handling
using System;
using System.IO;
class tryCatchDemo
{
static void Main(string[] args)
{
try
{
File.OpenRead("NonExistentFile");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
The output?
Exception Handling – Multiple “catch”s
try
{
int number = Convert.ToInt32(userInput);
}
catch (FormatException e)
{
Console.WriteLine("You must enter a number.");
}
catch (OverflowException e)
{
Console.WriteLine("Enter a smaller number.");
}
catch (Exception e)
{
Console.WriteLine("An unknown error occurred.");
}
Exception Handling
• Multiple catch statement?!
catch(FileNotFoundException e)
{
Console.WriteLine(e.ToString());
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
Exception Handling – finally keyword
class FinallyDemo
{
static void Main(string[] args)
{
FileStream outStream = null;
FileStream inStream = null;
try
{
outStream = File.OpenWrite("DestinationFile.txt");
inStream = File.OpenRead("BogusInputFile.txt");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (outStream!= null)
{
outStream.Close();
Console.WriteLine("outStream closed.");
}
if (inStream!= null)
{
inStream.Close();
Console.WriteLine("inStream closed.");
}
}
}
}
Throwing Exceptions
Throwing Exceptions
• Like this:
• But why?
public void CauseProblemsForTheWorld() //always up to no good...
{
throw new Exception("Just doing my job!");
}
Searching for a catch
• Caller chain is traversed backwards until a method with a matching catch clause is
found.
• If none is found => Program is aborted with a stack trace
• Exceptions don't have to be caught in C# (in contrast to Java)
Creating Exceptions
Creating Exceptions
• Let’s throw an exception when you over-eat Hamburgers!
• Now you can say:
public class AteTooManyHamburgersException : Exception
{
public int HamburgersEaten { get; set; }
public AteTooManyHamburgersException(int hamburgersEaten)
{
HamburgersEaten = hamburgersEaten;
}
}
try
{
EatSomeHamburgers(32);
}
catch(AteTooManyHamburgersException hamburgerException)
{
Console.WriteLine(hamburgerException.HamburgersEaten + " is too many hamburgers.");
}
Unsafe Code!
Unsafe Code!
• unsafe code == (code using explicit pointers and memory allocation) in C#
// The following fixed statement pins the location of
// the src and dst objects in memory so that they will
// not be moved by garbage collection.
fixed (byte* pSrc = src, pDst = dst)
{
byte* ps = pSrc;
byte* pd = pDst;
// Loop over the count in blocks of 4 bytes, copying an
// integer (4 bytes) at a time:
for (int n =0; n < count/4; n++)
{
*((int*)pd) = *((int*)ps);
pd += 4;
ps += 4;
}
Nullable Types
Nullable Types - The Concept
Nullable Types
• Declaration
DateTime? startDate;
Nullable Types
• Declaration
DateTime? startDate;
// You can assign a normal value to startDate like this:
startDate = DateTime.Now;
Nullable Types
• Declaration
DateTime? startDate;
// You can assign a normal value to startDate like this:
startDate = DateTime.Now;
// or you can assign null, like this:
startDate = null;
Nullable Types
• Declaration
// Here's another example that declares and initializes a
nullable int:
int? unitsInStock = 5;
Nullable Types
class Program
{
static void Main()
{
DateTime? startDate = DateTime.Now;
bool isNull = startDate == null;
Console.WriteLine("isNull: " + isNull);
}
}
Nullable Types
class Program
{
static void Main()
{
DateTime? startDate = DateTime.Now;
bool isNull = startDate == null;
Console.WriteLine("isNull: " + isNull);
}
}
isNull: False
Press any key to continue...
Nullable Types
class Program
{
static void Main()
{
int i = null;
}
}
Nullable Types
class Program
{
static void Main()
{
int i = null;
}
}
Compiler error, Can’t convert from null to type int
using keyword
using Directive - using statement
using Directive
using Directive
• The using Directive has two uses:
– To permit the use of types in a namespace so you do not have to qualify the use of a type in
that namespace:
– To create an alias for a namespace or a type:
using System.Text;
using Project = PC.MyCompany.Project;
using Directive
namespace PC
{
// Define an alias for the nested namespace.
using Project = PC.MyCompany.Project;
class A
{
void M()
{
// Use the alias
Project.MyClass mc = new Project.MyClass();
}
}
namespace MyCompany
{
namespace Project
{
public class MyClass { }
}
}
}
using Directive
namespace PC
{
// Define an alias for the nested namespace.
using Project = PC.MyCompany.Project;
class A
{
void M()
{
// Use the alias
Project.MyClass mc = new Project.MyClass();
}
}
namespace MyCompany
{
namespace Project
{
public class MyClass { }
}
}
}
using Directive
namespace PC
{
// Define an alias for the nested namespace.
using Project = PC.MyCompany.Project;
class A
{
void M()
{
// Use the alias
Project.MyClass mc = new Project.MyClass();
}
}
namespace MyCompany
{
namespace Project
{
public class MyClass { }
}
}
}
using Directive
namespace PC
{
// Define an alias for the nested namespace.
using Project = PC.MyCompany.Project;
class A
{
void M()
{
// Use the alias
Project.MyClass mc = new Project.MyClass();
}
}
namespace MyCompany
{
namespace Project
{
public class MyClass { }
}
}
}
using statement
using statement
• C#, through the.NET Framework common language runtime (CLR), automatically
releases the memory used to store objects that are no longer required.
• The release of memory is non-deterministic; memory is released whenever the
CLR decides to perform garbage collection. However, it is usually best to release
limited resources such as file handles and network connections as quickly as
possible.
using Directive
• Defines a scope, outside of which an object or objects will be disposed.
using (Font font1 = new Font("Arial", 10.0f))
{
// Use font1
}
using Directive
• Defines a scope, outside of which an object or objects will be disposed.
using (Font font1 = new Font("Arial", 10.0f))
{
// Use font1
}
using (Font font3 = new Font("Arial", 10.0f),
font4 = new Font("Arial", 10.0f))
{
// Use font3 and font4.
}
using Directive
class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}
void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main()
{
using (C c = new C())
{
c.UseLimitedResource();
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}
using Directive
class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}
void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main()
{
using (C c = new C())
{
c.UseLimitedResource();
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}
using Directive
class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}
void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main()
{
using (C c = new C())
{
c.UseLimitedResource();
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}
using Directive
class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}
void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main()
{
using (C c = new C())
{
c.UseLimitedResource();
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}
using Directive
class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}
void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main()
{
using (C c = new C())
{
c.UseLimitedResource();
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}
using Directive
class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}
void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main()
{
using (C c = new C())
{
c.UseLimitedResource();
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}
using Directive
class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}
void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main()
{
using (C c = new C())
{
c.UseLimitedResource();
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}
Using limited resource...
Disposing limited resource.
Now outside using statement.
Type Aliases
Type Aliases
• For instant naming we can use this for long type names:
• And then just using it as follow
using SB = System.Text.StringBuilder;
SB stringBuilder = new SB("InitialValue");
Files
Files, One Shot Reading
// Change the file path here to where you want it.
String path = @”C:/Users/Mhd/Desktop/test1.txt”;
string fileContents = File.ReadAllText(path);
string[] fileContentsByLine = File.ReadAllLines(path);
Files, One Shot Writing
// Change the file path here to where you want it.
String path = @”C:/Users/Mhd/Desktop/test1.txt”;
string informationToWrite = "Hello world!";
File.WriteAllText(path, informationToWrite);
string[] arrayOfInformation = new string[2];
arrayOfInformation[0] = "This is line 1";
arrayOfInformation[1] = "This is line 2";
File.WriteAllLines(path, arrayOfInformation);
Files
Reading and Writing on a Text-based Files
Files
• StreamWriter
– Object for writing a stream down
• StreamReader
– Object for reading a stream up
using System;
using System.IO;
public partial class Test
{
public static void Main()
{
string path = @"c:tempMyTest.txt";
// Create a file to write to.
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
// Open the file to read from.
using (StreamReader sr = new StreamReader(path))
{
string s = "";
while ((s = sr.ReadLine())!= null)
{
Console.WriteLine(s);
}
}
}
}
using System;
using System.IO;
public partial class Test
{
public static void Main()
{
string path = @"c:tempMyTest.txt";
// Create a file to write to.
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
// Open the file to read from.
using (StreamReader sr = new StreamReader(path))
{
string s = "";
while ((s = sr.ReadLine())!= null)
{
Console.WriteLine(s);
}
}
}
}
Hello
And
Welcome
Press any key to continue...
using System;
using System.IO;
public partial class Test
{
public static void Main()
{
string path = @"c:tempMyTest.txt";
// Create a file to write to.
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
// Open the file to read from.
using (StreamReader sr = new StreamReader(path))
{
string s = "";
while ((s = sr.ReadLine())!= null)
{
Console.WriteLine(s);
}
}
}
}
Hello
And
Welcome
Press any key to continue...
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:tempMyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine())!= null)
{
Console.WriteLine(s);
}
}
}
}
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:tempMyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine())!= null)
{
Console.WriteLine(s);
}
}
}
}
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:tempMyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine())!= null)
{
Console.WriteLine(s);
}
}
}
}
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:tempMyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine())!= null)
{
Console.WriteLine(s);
}
}
}
}
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:tempMyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine())!= null)
{
Console.WriteLine(s);
}
}
}
}
Reading and Writing on a Binary Files
BinaryWriter and BinaryReader
// Change the file path here to where you want it.
String path = @”C:/Users/Mhd/Desktop/test1.txt”;
FileStream fileStream = File.OpenWrite(path);
BinaryWriter binaryWriter = new BinaryWriter(fileStream);
binaryWriter.Write(2);
binaryWriter.Write("Hello");
binaryWriter.Flush();
binaryWriter.Close();
Class Diagram
Class Diagram
Windows Forms
Windows Forms
To learn more about Windows Forms,
visit my C++.NET course @
http://www.slideshare.net/ZGTRZGTR/
exactly the same as C#
That’s it for today!

Más contenido relacionado

La actualidad más candente

AST Transformations
AST TransformationsAST Transformations
AST Transformations
HamletDRC
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
Paulo Morgado
 

La actualidad más candente (20)

Closer look at classes
Closer look at classesCloser look at classes
Closer look at classes
 
The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
What is Pure Functional Programming, and how it can improve our application t...
What is Pure Functional Programming, and how it can improve our application t...What is Pure Functional Programming, and how it can improve our application t...
What is Pure Functional Programming, and how it can improve our application t...
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181
 
01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Java Polymorphism Part 2
Java Polymorphism Part 2Java Polymorphism Part 2
Java Polymorphism Part 2
 
The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181
 
Object Calisthenics em Go
Object Calisthenics em GoObject Calisthenics em Go
Object Calisthenics em Go
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185
 
Initial Java Core Concept
Initial Java Core ConceptInitial Java Core Concept
Initial Java Core Concept
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 

Similar a C# Starter L03-Utilities

String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
Shahjahan Samoon
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
Shahjahan Samoon
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
Connex
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
myrajendra
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
SyedHaroonShah4
 

Similar a C# Starter L03-Utilities (20)

String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
tick cross game
tick cross gametick cross game
tick cross game
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
Core C#
Core C#Core C#
Core C#
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
Strings in java
Strings in javaStrings in java
Strings in java
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrains
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 

Más de Mohammad Shaker

Más de Mohammad Shaker (20)

12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate
 
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
 
Interaction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with PsychologyInteraction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with Psychology
 
Short, Matters, Love - Passioneers Event 2015
Short, Matters, Love -  Passioneers Event 2015Short, Matters, Love -  Passioneers Event 2015
Short, Matters, Love - Passioneers Event 2015
 
Unity L01 - Game Development
Unity L01 - Game DevelopmentUnity L01 - Game Development
Unity L01 - Game Development
 
Android L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and WearablesAndroid L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and Wearables
 
Interaction Design L03 - Color
Interaction Design L03 - ColorInteraction Design L03 - Color
Interaction Design L03 - Color
 
Interaction Design L05 - Typography
Interaction Design L05 - TypographyInteraction Design L05 - Typography
Interaction Design L05 - Typography
 
Interaction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and CouplingInteraction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and Coupling
 
Android L05 - Storage
Android L05 - StorageAndroid L05 - Storage
Android L05 - Storage
 
Android L04 - Notifications and Threading
Android L04 - Notifications and ThreadingAndroid L04 - Notifications and Threading
Android L04 - Notifications and Threading
 
Android L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOSAndroid L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOS
 
Interaction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile ConstraintsInteraction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile Constraints
 
Interaction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and GridsInteraction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and Grids
 
Android L10 - Stores and Gaming
Android L10 - Stores and GamingAndroid L10 - Stores and Gaming
Android L10 - Stores and Gaming
 
Android L06 - Cloud / Parse
Android L06 - Cloud / ParseAndroid L06 - Cloud / Parse
Android L06 - Cloud / Parse
 
Android L08 - Google Maps and Utilities
Android L08 - Google Maps and UtilitiesAndroid L08 - Google Maps and Utilities
Android L08 - Google Maps and Utilities
 
Android L03 - Styles and Themes
Android L03 - Styles and Themes Android L03 - Styles and Themes
Android L03 - Styles and Themes
 
Android L02 - Activities and Adapters
Android L02 - Activities and AdaptersAndroid L02 - Activities and Adapters
Android L02 - Activities and Adapters
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 

C# Starter L03-Utilities

  • 1. Mohammad Shaker mohammadshaker.com C# Programming Course @ZGTRShaker 2011, 2012, 2013, 2014 C# Starter L03 – Utilities
  • 2. Today’s Agenda • const and readonly • Casting – Direct Casting – as Keyword • is Keyword • enums • Exception Handling • UnSafe Code • Nullable Types • using Keyword • Files • Class Diagram • Windows Forms
  • 4. const and readonly • const – Must be initialized in the time of declaration • readonly – keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class. public const int WEIGHT = 1000; public readonly int y = 5;
  • 5. const and readonly • const – Must be initialized in the time of declaration • readonly – keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class. public const int WEIGHT = 1000; public readonly int y = 5; public readonly int y = 5; public readonly int y;
  • 6. const and readonly • const – Must be initialized in the time of declaration • readonly – keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class. public const int WEIGHT = 1000; public readonly int y = 5; public readonly int y = 5; public readonly int y;
  • 9. void Example(object o) { // Casting string s = (string)o; // 1 (Direct Casting) // -OR- string s = o as string; // 2 (Casting with “as” Keyword) // -OR- string s = o.ToString(); // 3 Calling a method } Casting • What’s the difference? Output?
  • 10. void Example(object o) { // Casting string s = (string)o; // 1 (Direct Casting) // -OR- string s = o as string; // 2 (Casting with “as” Keyword) // -OR- string s = o.ToString(); // 3 Calling a method } Casting • What’s the difference? Output? Number (“1”) • If (o is not a string) Throws InvalidCastException if o is not a string. • Otherwise, assigns o to s, even if o is null.
  • 11. void Example(object o) { // Casting string s = (string)o; // 1 (Direct Casting) // -OR- string s = o as string; // 2 (Casting with “as” Keyword) // -OR- string s = o.ToString(); // 3 Calling a method } Casting • What’s the difference? Output? Number (“2”) • Assigns null to s if o is not a string or if o is null. • Otherwise assign to s “CAN’T BE A NULL VALUE” For this reason, you cannot use it with value types.
  • 12. void Example(object o) { // Casting string s = (string)o; // 1 (Direct Casting) // -OR- string s = o as string; // 2 (Casting with “as” Keyword) // -OR- string s = o.ToString(); // 3 Calling a method } Casting • What’s the difference? Output? Number(“3”) • Causes a NullReferenceException of o is null. • Assigns whatever o.ToString() returns to s, no matter what type o is.
  • 13. void Example(object o) { // Casting string s = (string)o; // 1 (Direct Casting) // -OR- string s = o as string; // 2 (Casting with “as” Keyword) // -OR- string s = o.ToString(); // 3 Calling a method } Casting • What’s the difference? Output? 1. Throws InvalidCastException if o is not a string. Otherwise, assigns o to s, even if o is null. 2. Assigns null to s if o is not a string or if o is null. Otherwise, assigns o to s. For this reason, you cannot use it with value types. 3. Causes a NullReferenceException of o is null. Assigns whatever o.ToString() returns to s, no matter what type o is.
  • 14. void Example(object o) { // I swear o is a string, C# compiler! I’m ordering you to cast, I know what am doing! string s = (string)o; // 1 (Direct Casting) // I Donna know whether o is a string or not, try a cast and tell me! string s = o as string; // 2 (Casting with “as” Keyword) // Am programming badly with this code! string s = o.ToString(); // 3 Calling a method } Casting • Meaning!
  • 15. void Example(object o) { // I swear o is a string, C# compiler! I’m ordering you to cast, I know what am doing! string s = (string)o; // 1 (Direct Casting) // I Donna know whether o is a string or not, try a cast and tell me! string s = o as string; // 2 (Casting with “as” Keyword) // Am programming badly with this code! string s = o.ToString(); // 3 Calling a method } Casting • Meaning! “as” casting will never throw an exception, while “Direct cast” can.
  • 16. void Example(object o) { // I swear o is a string, C# compiler! I’m ordering you to cast, I know what am doing! string s = (string)o; // 1 (Direct Casting) // I Donna know whether o is a string or not, try a cast and tell me! string s = o as string; // 2 (Casting with “as” Keyword) // Am programming badly with this code! string s = o.ToString(); // 3 Calling a method } Casting • Meaning! “as” casting will never throw an exception, while “Direct cast” can. “as” cannot be used with value types (non-nullable types).
  • 17. using System; class MyClass1{} class MyClass2{} public class IsTest { public static void Main() { object[] myObjects = new object[6]; myObjects[0] = new MyClass1(); myObjects[1] = new MyClass2(); myObjects[2] = "hello"; myObjects[3] = 123; myObjects[4] = 123.4; myObjects[5] = null; for (int i = 0; i < myObjects.Length; ++i) { string s = myObjects[i] as string; Console.Write("{0}:", i); if (s!= null) Console.WriteLine("'" + s + "'"); else Console.WriteLine("not a string"); } } } Casting
  • 18. using System; class MyClass1{} class MyClass2{} public class IsTest { public static void Main() { object[] myObjects = new object[6]; myObjects[0] = new MyClass1(); myObjects[1] = new MyClass2(); myObjects[2] = "hello"; myObjects[3] = 123; myObjects[4] = 123.4; myObjects[5] = null; for (int i = 0; i < myObjects.Length; ++i) { string s = myObjects[i] as string; Console.Write("{0}:", i); if (s!= null) Console.WriteLine("'" + s + "'"); else Console.WriteLine("not a string"); } } } Casting 0:not a string 1:not a string 2:'hello' 3:not a string 4:not a string 5:not a string
  • 20. “is” Keyword • The is operator is used to check whether the run-time type of an object is compatible with a given type. • The is operator is used in an expression of the form: expression is type
  • 21. “is” Keyword • Let’s have the following example class Class1{} class Class2{}
  • 22. “is” Keyword public class IsTest { public static void Test(object o) { Class1 a; Class2 b; if (o is Class1) { Console.WriteLine("o is Class1"); a = (Class1)o; // do something with a } else if (o is Class2) { Console.WriteLine("o is Class2"); b = (Class2)o; // do something with b } else { Console.WriteLine("o is neither Class1 nor Class2."); } } public static void Main() { Class1 c1 = new Class1(); Class2 c2 = new Class2(); Test(c1); Test(c2); Test("a string"); } }
  • 23. “is” Keyword public class IsTest { public static void Test(object o) { Class1 a; Class2 b; if (o is Class1) { Console.WriteLine("o is Class1"); a = (Class1)o; // do something with a } else if (o is Class2) { Console.WriteLine("o is Class2"); b = (Class2)o; // do something with b } else { Console.WriteLine("o is neither Class1 nor Class2."); } } public static void Main() { Class1 c1 = new Class1(); Class2 c2 = new Class2(); Test(c1); Test(c2); Test("a string"); } } o is Class1 o is Class2 o is neither Class1 nor Class2. Press any key to continue...
  • 24. enum
  • 25. enum • As easy as: • And that’s it! // You define enumerations outside of other classes. public enum DaysOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; DaysOfWeek dayOfWeek = DaysOfWeek.Monday; if(dayOfWeek == Wednesday) { // Do something here }
  • 28. Exception Handling using System; using System.IO; class tryCatchDemo { static void Main(string[] args) { try { File.OpenRead("NonExistentFile"); } catch(Exception ex) { Console.WriteLine(ex.ToString()); } } } The output?
  • 29. Exception Handling using System; using System.IO; class tryCatchDemo { static void Main(string[] args) { try { File.OpenRead("NonExistentFile"); } catch(Exception ex) { Console.WriteLine(ex.ToString()); } } } The output?
  • 30. Exception Handling using System; using System.IO; class tryCatchDemo { static void Main(string[] args) { try { File.OpenRead("NonExistentFile"); } catch(Exception ex) { Console.WriteLine(ex.ToString()); } } } The output?
  • 31. Exception Handling – Multiple “catch”s try { int number = Convert.ToInt32(userInput); } catch (FormatException e) { Console.WriteLine("You must enter a number."); } catch (OverflowException e) { Console.WriteLine("Enter a smaller number."); } catch (Exception e) { Console.WriteLine("An unknown error occurred."); }
  • 32. Exception Handling • Multiple catch statement?! catch(FileNotFoundException e) { Console.WriteLine(e.ToString()); } catch(Exception ex) { Console.WriteLine(ex.ToString()); }
  • 33. Exception Handling – finally keyword class FinallyDemo { static void Main(string[] args) { FileStream outStream = null; FileStream inStream = null; try { outStream = File.OpenWrite("DestinationFile.txt"); inStream = File.OpenRead("BogusInputFile.txt"); } catch(Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (outStream!= null) { outStream.Close(); Console.WriteLine("outStream closed."); } if (inStream!= null) { inStream.Close(); Console.WriteLine("inStream closed."); } } } }
  • 35. Throwing Exceptions • Like this: • But why? public void CauseProblemsForTheWorld() //always up to no good... { throw new Exception("Just doing my job!"); }
  • 36. Searching for a catch • Caller chain is traversed backwards until a method with a matching catch clause is found. • If none is found => Program is aborted with a stack trace • Exceptions don't have to be caught in C# (in contrast to Java)
  • 38. Creating Exceptions • Let’s throw an exception when you over-eat Hamburgers! • Now you can say: public class AteTooManyHamburgersException : Exception { public int HamburgersEaten { get; set; } public AteTooManyHamburgersException(int hamburgersEaten) { HamburgersEaten = hamburgersEaten; } } try { EatSomeHamburgers(32); } catch(AteTooManyHamburgersException hamburgerException) { Console.WriteLine(hamburgerException.HamburgersEaten + " is too many hamburgers."); }
  • 40. Unsafe Code! • unsafe code == (code using explicit pointers and memory allocation) in C# // The following fixed statement pins the location of // the src and dst objects in memory so that they will // not be moved by garbage collection. fixed (byte* pSrc = src, pDst = dst) { byte* ps = pSrc; byte* pd = pDst; // Loop over the count in blocks of 4 bytes, copying an // integer (4 bytes) at a time: for (int n =0; n < count/4; n++) { *((int*)pd) = *((int*)ps); pd += 4; ps += 4; }
  • 42. Nullable Types - The Concept
  • 44. Nullable Types • Declaration DateTime? startDate; // You can assign a normal value to startDate like this: startDate = DateTime.Now;
  • 45. Nullable Types • Declaration DateTime? startDate; // You can assign a normal value to startDate like this: startDate = DateTime.Now; // or you can assign null, like this: startDate = null;
  • 46. Nullable Types • Declaration // Here's another example that declares and initializes a nullable int: int? unitsInStock = 5;
  • 47. Nullable Types class Program { static void Main() { DateTime? startDate = DateTime.Now; bool isNull = startDate == null; Console.WriteLine("isNull: " + isNull); } }
  • 48. Nullable Types class Program { static void Main() { DateTime? startDate = DateTime.Now; bool isNull = startDate == null; Console.WriteLine("isNull: " + isNull); } } isNull: False Press any key to continue...
  • 49. Nullable Types class Program { static void Main() { int i = null; } }
  • 50. Nullable Types class Program { static void Main() { int i = null; } } Compiler error, Can’t convert from null to type int
  • 51. using keyword using Directive - using statement
  • 53. using Directive • The using Directive has two uses: – To permit the use of types in a namespace so you do not have to qualify the use of a type in that namespace: – To create an alias for a namespace or a type: using System.Text; using Project = PC.MyCompany.Project;
  • 54. using Directive namespace PC { // Define an alias for the nested namespace. using Project = PC.MyCompany.Project; class A { void M() { // Use the alias Project.MyClass mc = new Project.MyClass(); } } namespace MyCompany { namespace Project { public class MyClass { } } } }
  • 55. using Directive namespace PC { // Define an alias for the nested namespace. using Project = PC.MyCompany.Project; class A { void M() { // Use the alias Project.MyClass mc = new Project.MyClass(); } } namespace MyCompany { namespace Project { public class MyClass { } } } }
  • 56. using Directive namespace PC { // Define an alias for the nested namespace. using Project = PC.MyCompany.Project; class A { void M() { // Use the alias Project.MyClass mc = new Project.MyClass(); } } namespace MyCompany { namespace Project { public class MyClass { } } } }
  • 57. using Directive namespace PC { // Define an alias for the nested namespace. using Project = PC.MyCompany.Project; class A { void M() { // Use the alias Project.MyClass mc = new Project.MyClass(); } } namespace MyCompany { namespace Project { public class MyClass { } } } }
  • 59. using statement • C#, through the.NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. • The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.
  • 60. using Directive • Defines a scope, outside of which an object or objects will be disposed. using (Font font1 = new Font("Arial", 10.0f)) { // Use font1 }
  • 61. using Directive • Defines a scope, outside of which an object or objects will be disposed. using (Font font1 = new Font("Arial", 10.0f)) { // Use font1 } using (Font font3 = new Font("Arial", 10.0f), font4 = new Font("Arial", 10.0f)) { // Use font3 and font4. }
  • 62. using Directive class C : IDisposable { public void UseLimitedResource() { Console.WriteLine("Using limited resource..."); } void IDisposable.Dispose() { Console.WriteLine("Disposing limited resource."); } } class Program { static void Main() { using (C c = new C()) { c.UseLimitedResource(); } Console.WriteLine("Now outside using statement."); Console.ReadLine(); } }
  • 63. using Directive class C : IDisposable { public void UseLimitedResource() { Console.WriteLine("Using limited resource..."); } void IDisposable.Dispose() { Console.WriteLine("Disposing limited resource."); } } class Program { static void Main() { using (C c = new C()) { c.UseLimitedResource(); } Console.WriteLine("Now outside using statement."); Console.ReadLine(); } }
  • 64. using Directive class C : IDisposable { public void UseLimitedResource() { Console.WriteLine("Using limited resource..."); } void IDisposable.Dispose() { Console.WriteLine("Disposing limited resource."); } } class Program { static void Main() { using (C c = new C()) { c.UseLimitedResource(); } Console.WriteLine("Now outside using statement."); Console.ReadLine(); } }
  • 65. using Directive class C : IDisposable { public void UseLimitedResource() { Console.WriteLine("Using limited resource..."); } void IDisposable.Dispose() { Console.WriteLine("Disposing limited resource."); } } class Program { static void Main() { using (C c = new C()) { c.UseLimitedResource(); } Console.WriteLine("Now outside using statement."); Console.ReadLine(); } }
  • 66. using Directive class C : IDisposable { public void UseLimitedResource() { Console.WriteLine("Using limited resource..."); } void IDisposable.Dispose() { Console.WriteLine("Disposing limited resource."); } } class Program { static void Main() { using (C c = new C()) { c.UseLimitedResource(); } Console.WriteLine("Now outside using statement."); Console.ReadLine(); } }
  • 67. using Directive class C : IDisposable { public void UseLimitedResource() { Console.WriteLine("Using limited resource..."); } void IDisposable.Dispose() { Console.WriteLine("Disposing limited resource."); } } class Program { static void Main() { using (C c = new C()) { c.UseLimitedResource(); } Console.WriteLine("Now outside using statement."); Console.ReadLine(); } }
  • 68. using Directive class C : IDisposable { public void UseLimitedResource() { Console.WriteLine("Using limited resource..."); } void IDisposable.Dispose() { Console.WriteLine("Disposing limited resource."); } } class Program { static void Main() { using (C c = new C()) { c.UseLimitedResource(); } Console.WriteLine("Now outside using statement."); Console.ReadLine(); } } Using limited resource... Disposing limited resource. Now outside using statement.
  • 70. Type Aliases • For instant naming we can use this for long type names: • And then just using it as follow using SB = System.Text.StringBuilder; SB stringBuilder = new SB("InitialValue");
  • 71. Files
  • 72. Files, One Shot Reading // Change the file path here to where you want it. String path = @”C:/Users/Mhd/Desktop/test1.txt”; string fileContents = File.ReadAllText(path); string[] fileContentsByLine = File.ReadAllLines(path);
  • 73. Files, One Shot Writing // Change the file path here to where you want it. String path = @”C:/Users/Mhd/Desktop/test1.txt”; string informationToWrite = "Hello world!"; File.WriteAllText(path, informationToWrite); string[] arrayOfInformation = new string[2]; arrayOfInformation[0] = "This is line 1"; arrayOfInformation[1] = "This is line 2"; File.WriteAllLines(path, arrayOfInformation);
  • 74. Files Reading and Writing on a Text-based Files
  • 75. Files • StreamWriter – Object for writing a stream down • StreamReader – Object for reading a stream up
  • 76. using System; using System.IO; public partial class Test { public static void Main() { string path = @"c:tempMyTest.txt"; // Create a file to write to. using (StreamWriter sw = new StreamWriter(path)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } // Open the file to read from. using (StreamReader sr = new StreamReader(path)) { string s = ""; while ((s = sr.ReadLine())!= null) { Console.WriteLine(s); } } } }
  • 77. using System; using System.IO; public partial class Test { public static void Main() { string path = @"c:tempMyTest.txt"; // Create a file to write to. using (StreamWriter sw = new StreamWriter(path)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } // Open the file to read from. using (StreamReader sr = new StreamReader(path)) { string s = ""; while ((s = sr.ReadLine())!= null) { Console.WriteLine(s); } } } } Hello And Welcome Press any key to continue...
  • 78. using System; using System.IO; public partial class Test { public static void Main() { string path = @"c:tempMyTest.txt"; // Create a file to write to. using (StreamWriter sw = new StreamWriter(path)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } // Open the file to read from. using (StreamReader sr = new StreamReader(path)) { string s = ""; while ((s = sr.ReadLine())!= null) { Console.WriteLine(s); } } } } Hello And Welcome Press any key to continue...
  • 79. using System; using System.IO; class Test { public static void Main() { string path = @"c:tempMyTest.txt"; if (!File.Exists(path)) { // Create a file to write to. using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } } // Open the file to read from. using (StreamReader sr = File.OpenText(path)) { string s = ""; while ((s = sr.ReadLine())!= null) { Console.WriteLine(s); } } } }
  • 80. using System; using System.IO; class Test { public static void Main() { string path = @"c:tempMyTest.txt"; if (!File.Exists(path)) { // Create a file to write to. using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } } // Open the file to read from. using (StreamReader sr = File.OpenText(path)) { string s = ""; while ((s = sr.ReadLine())!= null) { Console.WriteLine(s); } } } }
  • 81. using System; using System.IO; class Test { public static void Main() { string path = @"c:tempMyTest.txt"; if (!File.Exists(path)) { // Create a file to write to. using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } } // Open the file to read from. using (StreamReader sr = File.OpenText(path)) { string s = ""; while ((s = sr.ReadLine())!= null) { Console.WriteLine(s); } } } }
  • 82. using System; using System.IO; class Test { public static void Main() { string path = @"c:tempMyTest.txt"; if (!File.Exists(path)) { // Create a file to write to. using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } } // Open the file to read from. using (StreamReader sr = File.OpenText(path)) { string s = ""; while ((s = sr.ReadLine())!= null) { Console.WriteLine(s); } } } }
  • 83. using System; using System.IO; class Test { public static void Main() { string path = @"c:tempMyTest.txt"; if (!File.Exists(path)) { // Create a file to write to. using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } } // Open the file to read from. using (StreamReader sr = File.OpenText(path)) { string s = ""; while ((s = sr.ReadLine())!= null) { Console.WriteLine(s); } } } }
  • 84. Reading and Writing on a Binary Files BinaryWriter and BinaryReader // Change the file path here to where you want it. String path = @”C:/Users/Mhd/Desktop/test1.txt”; FileStream fileStream = File.OpenWrite(path); BinaryWriter binaryWriter = new BinaryWriter(fileStream); binaryWriter.Write(2); binaryWriter.Write("Hello"); binaryWriter.Flush(); binaryWriter.Close();
  • 87.
  • 88.
  • 91. To learn more about Windows Forms, visit my C++.NET course @ http://www.slideshare.net/ZGTRZGTR/ exactly the same as C#
  • 92. That’s it for today!