Csharp4 objects and_types

Abed Bukhari
Abed BukhariEntrepreneur à KomraVision GmbH
Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com
Objects  & Types What’s in This Chapter? -The differences between classes and structs - Class members - Passing values by value and by reference - Method overloading - Constructors and static constructors - Read-only fields - Partial classes - Static classes - The Object class, from which all other types are derived
Classes and Structs ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],struct PhoneCustomerStruct { public const string DayOfSendingBill = "Monday"; public int CustomerID; public string FirstName; public string LastName; } PhoneCustomer   myCustomer =  new   PhoneCustomer (); // works for a class PhoneCustomerStruct   myCustomer2 =  new   PhoneCustomerStruct ();// works for a struct
Classes -  Class Members ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Classes -  Class Members (cont) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Classes -  Class Members (cont) ,[object Object],[object Object]
Classes –  Declaring a Method [ modifiers ]  return_type   MethodName ([parameters]) { //  Method body } Ex: public bool IsSquare(Rectangle rect) { return (rect.Height == rect.Width); } Ex: many returns public bool IsPositive(int value) { if (value < 0) return false; return true; }
Classes –  Invoking Methods MathTesting.cs on Visual Studio 2010 Demo
Classes –  Passing Parameters to Methods ParametersTesting.cs  on Visual Studio 2010 Demo
Classes –  ref Parameters static void SomeFunction(int[] ints, ref int i) { ints[0] = 100; i = 100; // The change to i will persist after SomeFunction() exits. } You will also need to add the ref keyword when you invoke the method: SomeFunction(ints, ref i);. Finally, it is also important to understand that C# continues to apply initialization requirements to parameters passed to methods. Any variable must be initialized before it is passed into a method, whether it is passed in by value or by reference.
Classes –  out Parameters static void SomeFunction(out int i) { i = 100; } public static int Main() { int i; // note how i is declared but not initialized. SomeFunction(out i); Console.WriteLine(i); return 0; }
Classes –  Named Arguments string FullName(string firstName, string lastName) { return firstName + &quot; &quot; + lastName; } The following method calls will return the same full name: FullName(“Abed&quot;, “Bukhari&quot;); FullName(lastName: “Bukhari&quot;, firstName: “Abed&quot;);
Classes –  Optional Arguments incorrect: void TestMethod(int optionalNumber = 10, int notOptionalNumber) { System.Console.Write(optionalNumber + notOptionalNumber); } For this method to work, the  optionalNumber  parameter would have to be defined  last . Correct : void TestMethod(int notOptionalNumber, int optionalNumber = 10) { System.Console.Write(optionalNumber + notOptionalNumber); }
Classes –  Method Overloading class ResultDisplayer { void DisplayResult(string result) { // implementation } void DisplayResult(int result) { // implementation } } - It is not sufficient for two methods to differ only in their return type. - It is not sufficient for two methods to differ only by  virtue of a parameter having been declared as ref or out.
Classes –  Method Overloading cont If optional parameters won’t work for you, then you need to use method overloading to achieve the same effect: class MyClass { int DoSomething(int x) // want 2nd parameter with default value 10 { DoSomething(x, 10); } int DoSomething(int x, int y) { // implementation } }
Classes –  Properties // mainForm is of type System.Windows.Forms mainForm.Height = 400; To define a property in C#, you use the following syntax: public string SomeProperty { get { return &quot;This is the property value.&quot;; } set { // do whatever needs to be done to set the property. } }
Classes –  Properties cont. private int age; public int Age { get { return age; } set { age = value; } }
Classes –  Read-Only and Write-Only Properties private string name; public string Name { get { return Name; } }
Classes –  Access Modifiers for Properties public string Name { get { return _name; } private set { _name = value; } }
Classes –  Auto - Implemented Properties public string Age {get; set;} The declaration private int age; is not needed. The compiler will create this automatically. By using auto - implemented properties, validation of the property cannot be done at the property set. So in the previous example we could not have checked to see if an invalid age is set. Also, both accessors must be present. So an attempt to make a property read - only would cause an error: public string Age {get;} However, the access level of each accessor can be different. So the following is acceptable: public string Age {get; private set;}
Classes –  Constructors public class MyClass { public MyClass() { } // rest of class definition // overloads: public MyClass() // zeroparameter constructor { // construction code } public MyClass(int number) // another overload { // construction code }
Classes –  Constructors cont. public class MyNumber { private int number; public MyNumber(int number) { this.number = number; } } This code also illustrates typical use of the this keyword to distinguish member fields from parameters of the same name. If you now try instantiating a MyNumber object using a no-parameter constructor, you will get a compilation error: MyNumber numb = new MyNumber(); // causes compilation error
Classes –  Constructors cont. We should mention that it is possible to define constructors as private or protected, so that they are invisible to code in unrelated classes too: public class MyNumber { private int number; private MyNumber(int number) // another overload { this.number = number; } } // Notes - If your class serves only as a container for some static members or properties and  therefore should never be instantiated - If you want the class to only ever be instantiated by calling some static member function (this is the so-called class factory approach to object instantiation)
Classes –  Static Constructors class MyClass { static MyClass() { // initialization code } // rest of class definition }
Classes –  Static Constructors cont namespace Najah.ProCSharp.StaticConstructorSample { public class UserPreferences { public static readonly Color BackColor; static UserPreferences() { DateTime now = DateTime.Now; if (now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday) BackColor = Color.Green; else BackColor = Color.Red; } private UserPreferences() { } }}
Classes –  Static Constructors cont class MainEntryPoint { static void Main(string[] args) { Console.WriteLine(&quot;User-preferences: BackColor is: &quot; + UserPreferences.BackColor.ToString()); } } Compiling and running this code results in this output: User-preferences: BackColor is: Color [Red]
Classes –  Calling Constructors from Other Constructors class Car { private string description; private uint nWheels; public Car(string description, uint nWheels) { this.description = description; this.nWheels = nWheels; } public Car(string description) { this.description = description; this.nWheels = 4; } // etc.
Classes –  Calling Constructors from Other Constructors cont class Car { private string description; private uint nWheels; public Car(string description, uint nWheels) { this.description = description; this.nWheels = nWheels; } public Car(string description): this(description, 4) { } // etc
Classes –  Calling Constructors from Other Constructors cont class Car { private string description; private uint nWheels; public Car(string description, uint nWheels) { this.description = description; this.nWheels = nWheels; } public Car(string description): this(description, 4) { } // etc Car myCar = new Car(&quot;Proton Persona&quot;);
Classes –  readonly fields public class DocumentEditor { public static readonly uint MaxDocuments; static DocumentEditor() { MaxDocuments = DoSomethingToFindOutMaxNumber(); } }
Classes –  readonly fields cont. public class Document { public readonly DateTime CreationDate; public Document() { // Read in creation date from file. Assume result is 1 Jan 2002 // but in general this can be different for different instances // of the class CreationDate = new DateTime(2002, 1, 1); } } CreationDate and MaxDocuments in the previous code snippet are treated like any other field, except that because they are read-only, they cannot be assigned outside the constructors: void SomeMethod() { MaxDocuments = 10; // compilation error here. MaxDocuments is readonly }
Anonymous Types Types without names : var captain = new {FirstName = “Ahmad&quot;, MiddleName = “M&quot;, LastName = “Test&quot;};
Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com
1 sur 33

Recommandé

Constructors and destructors in C++ part 2 par
Constructors and destructors in C++ part 2Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2Lovely Professional University
532 vues42 diapositives
Class and object par
Class and objectClass and object
Class and objectprabhat kumar
100 vues27 diapositives
Interfaces in JAVA !! why?? par
Interfaces in JAVA !!  why??Interfaces in JAVA !!  why??
Interfaces in JAVA !! why??vedprakashrai
1.1K vues7 diapositives
Interface par
InterfaceInterface
Interfacekamal kotecha
15.4K vues28 diapositives
Polymorphism par
PolymorphismPolymorphism
Polymorphismprabhat kumar
94 vues25 diapositives
JAVA Notes - All major concepts covered with examples par
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
2.7K vues10 diapositives

Contenu connexe

Tendances

Java Reflection par
Java ReflectionJava Reflection
Java Reflectionelliando dias
964 vues36 diapositives
Inheritance par
InheritanceInheritance
InheritancePranali Chaudhari
4.5K vues60 diapositives
Java interfaces & abstract classes par
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
8.1K vues47 diapositives
Inheritance par
InheritanceInheritance
Inheritanceprabhat kumar
76 vues24 diapositives
04cpp inh par
04cpp inh04cpp inh
04cpp inhJihin Raju
220 vues10 diapositives
Java Reflection Concept and Working par
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and WorkingSoftware Productivity Strategists, Inc
696 vues41 diapositives

Tendances(20)

Java interfaces & abstract classes par Shreyans Pathak
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
Shreyans Pathak8.1K vues
Abstract & Interface par Linh Lê
Abstract & InterfaceAbstract & Interface
Abstract & Interface
Linh Lê1.2K vues
Reflection in java par upen.rockin
Reflection in javaReflection in java
Reflection in java
upen.rockin9.4K vues
Object Oriented Programming with Java par backdoor
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor13.8K vues
Chapter 02: Classes Objects and Methods Java by Tushar B Kute par Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute8.4K vues
Advanced Reflection in Java par kim.mens
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
kim.mens1.6K vues
OBJECT ORIENTED PROGRAMING IN C++ par Dev Chauhan
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
Dev Chauhan38 vues
Core java notes with examples par bindur87
Core java notes with examplesCore java notes with examples
Core java notes with examples
bindur87724 vues

En vedette

Airindia par
AirindiaAirindia
AirindiaAks singh
352 vues10 diapositives
Proyecto de investigacion par
Proyecto de investigacionProyecto de investigacion
Proyecto de investigacion2732910
277 vues3 diapositives
Vygostky and the education of infants and toddlers par
Vygostky and the education of infants and toddlersVygostky and the education of infants and toddlers
Vygostky and the education of infants and toddlers072771
5.6K vues39 diapositives
Ozone mobile media par
Ozone mobile mediaOzone mobile media
Ozone mobile mediaSriRam Vanchinathan
580 vues19 diapositives
Csharp4 arrays and_tuples par
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuplesAbed Bukhari
897 vues24 diapositives
Csharp4 delegates lambda_and_events par
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsAbed Bukhari
1.5K vues22 diapositives

En vedette(7)

Proyecto de investigacion par 2732910
Proyecto de investigacionProyecto de investigacion
Proyecto de investigacion
2732910277 vues
Vygostky and the education of infants and toddlers par 072771
Vygostky and the education of infants and toddlersVygostky and the education of infants and toddlers
Vygostky and the education of infants and toddlers
0727715.6K vues
Csharp4 arrays and_tuples par Abed Bukhari
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
Abed Bukhari897 vues
Csharp4 delegates lambda_and_events par Abed Bukhari
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
Abed Bukhari1.5K vues
Gobernacion sonsonate par Adalberto
Gobernacion sonsonateGobernacion sonsonate
Gobernacion sonsonate
Adalberto473 vues

Similaire à Csharp4 objects and_types

Chapter 4 - Defining Your Own Classes - Part I par
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IEduardo Bergavera
1.7K vues49 diapositives
Java căn bản - Chapter4 par
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4Vince Vo
435 vues49 diapositives
OOP and C++Classes par
OOP and C++ClassesOOP and C++Classes
OOP and C++ClassesMuhammadHuzaifa981023
26 vues17 diapositives
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ... par
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...Igalia
83 vues49 diapositives
Defining classes-and-objects-1.0 par
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
1.2K vues53 diapositives
9781439035665 ppt ch08 par
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08Terry Yoast
328 vues62 diapositives

Similaire à Csharp4 objects and_types(20)

Chapter 4 - Defining Your Own Classes - Part I par Eduardo Bergavera
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera1.7K vues
Java căn bản - Chapter4 par Vince Vo
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
Vince Vo435 vues
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ... par Igalia
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...
Implementing one feature set in two JavaScript engines (Web Engines Hackfest ...
Igalia83 vues
9781439035665 ppt ch08 par Terry Yoast
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast328 vues
Advanced c# par saranuru
Advanced c#Advanced c#
Advanced c#
saranuru539 vues
14. Defining Classes par Intro C# Book
14. Defining Classes14. Defining Classes
14. Defining Classes
Intro C# Book107.2K vues
C++ classes tutorials par akreyi
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
akreyi272 vues
Chapter 7 - Defining Your Own Classes - Part II par Eduardo Bergavera
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
Classes, objects and methods par farhan amjad
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
farhan amjad2.7K vues

Dernier

Kyo - Functional Scala 2023.pdf par
Kyo - Functional Scala 2023.pdfKyo - Functional Scala 2023.pdf
Kyo - Functional Scala 2023.pdfFlavio W. Brasil
368 vues92 diapositives
20231123_Camunda Meetup Vienna.pdf par
20231123_Camunda Meetup Vienna.pdf20231123_Camunda Meetup Vienna.pdf
20231123_Camunda Meetup Vienna.pdfPhactum Softwareentwicklung GmbH
41 vues73 diapositives
HTTP headers that make your website go faster - devs.gent November 2023 par
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023Thijs Feryn
22 vues151 diapositives
virtual reality.pptx par
virtual reality.pptxvirtual reality.pptx
virtual reality.pptxG036GaikwadSnehal
11 vues15 diapositives
Scaling Knowledge Graph Architectures with AI par
Scaling Knowledge Graph Architectures with AIScaling Knowledge Graph Architectures with AI
Scaling Knowledge Graph Architectures with AIEnterprise Knowledge
30 vues15 diapositives
Melek BEN MAHMOUD.pdf par
Melek BEN MAHMOUD.pdfMelek BEN MAHMOUD.pdf
Melek BEN MAHMOUD.pdfMelekBenMahmoud
14 vues1 diapositive

Dernier(20)

HTTP headers that make your website go faster - devs.gent November 2023 par Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn22 vues
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... par James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson85 vues
6g - REPORT.pdf par Liveplex
6g - REPORT.pdf6g - REPORT.pdf
6g - REPORT.pdf
Liveplex10 vues
Special_edition_innovator_2023.pdf par WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2217 vues
Powerful Google developer tools for immediate impact! (2023-24) par wesley chun
Powerful Google developer tools for immediate impact! (2023-24)Powerful Google developer tools for immediate impact! (2023-24)
Powerful Google developer tools for immediate impact! (2023-24)
wesley chun10 vues
Igniting Next Level Productivity with AI-Infused Data Integration Workflows par Safe Software
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Safe Software263 vues
Future of AR - Facebook Presentation par ssuserb54b561
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
ssuserb54b56114 vues
PharoJS - Zürich Smalltalk Group Meetup November 2023 par Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi127 vues
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf par Dr. Jimmy Schwarzkopf
STKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdfSTKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdf
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf

Csharp4 objects and_types

  • 1. Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com
  • 2. Objects & Types What’s in This Chapter? -The differences between classes and structs - Class members - Passing values by value and by reference - Method overloading - Constructors and static constructors - Read-only fields - Partial classes - Static classes - The Object class, from which all other types are derived
  • 3.
  • 4.
  • 5.
  • 6.
  • 7. Classes – Declaring a Method [ modifiers ] return_type MethodName ([parameters]) { // Method body } Ex: public bool IsSquare(Rectangle rect) { return (rect.Height == rect.Width); } Ex: many returns public bool IsPositive(int value) { if (value < 0) return false; return true; }
  • 8. Classes – Invoking Methods MathTesting.cs on Visual Studio 2010 Demo
  • 9. Classes – Passing Parameters to Methods ParametersTesting.cs on Visual Studio 2010 Demo
  • 10. Classes – ref Parameters static void SomeFunction(int[] ints, ref int i) { ints[0] = 100; i = 100; // The change to i will persist after SomeFunction() exits. } You will also need to add the ref keyword when you invoke the method: SomeFunction(ints, ref i);. Finally, it is also important to understand that C# continues to apply initialization requirements to parameters passed to methods. Any variable must be initialized before it is passed into a method, whether it is passed in by value or by reference.
  • 11. Classes – out Parameters static void SomeFunction(out int i) { i = 100; } public static int Main() { int i; // note how i is declared but not initialized. SomeFunction(out i); Console.WriteLine(i); return 0; }
  • 12. Classes – Named Arguments string FullName(string firstName, string lastName) { return firstName + &quot; &quot; + lastName; } The following method calls will return the same full name: FullName(“Abed&quot;, “Bukhari&quot;); FullName(lastName: “Bukhari&quot;, firstName: “Abed&quot;);
  • 13. Classes – Optional Arguments incorrect: void TestMethod(int optionalNumber = 10, int notOptionalNumber) { System.Console.Write(optionalNumber + notOptionalNumber); } For this method to work, the optionalNumber parameter would have to be defined last . Correct : void TestMethod(int notOptionalNumber, int optionalNumber = 10) { System.Console.Write(optionalNumber + notOptionalNumber); }
  • 14. Classes – Method Overloading class ResultDisplayer { void DisplayResult(string result) { // implementation } void DisplayResult(int result) { // implementation } } - It is not sufficient for two methods to differ only in their return type. - It is not sufficient for two methods to differ only by virtue of a parameter having been declared as ref or out.
  • 15. Classes – Method Overloading cont If optional parameters won’t work for you, then you need to use method overloading to achieve the same effect: class MyClass { int DoSomething(int x) // want 2nd parameter with default value 10 { DoSomething(x, 10); } int DoSomething(int x, int y) { // implementation } }
  • 16. Classes – Properties // mainForm is of type System.Windows.Forms mainForm.Height = 400; To define a property in C#, you use the following syntax: public string SomeProperty { get { return &quot;This is the property value.&quot;; } set { // do whatever needs to be done to set the property. } }
  • 17. Classes – Properties cont. private int age; public int Age { get { return age; } set { age = value; } }
  • 18. Classes – Read-Only and Write-Only Properties private string name; public string Name { get { return Name; } }
  • 19. Classes – Access Modifiers for Properties public string Name { get { return _name; } private set { _name = value; } }
  • 20. Classes – Auto - Implemented Properties public string Age {get; set;} The declaration private int age; is not needed. The compiler will create this automatically. By using auto - implemented properties, validation of the property cannot be done at the property set. So in the previous example we could not have checked to see if an invalid age is set. Also, both accessors must be present. So an attempt to make a property read - only would cause an error: public string Age {get;} However, the access level of each accessor can be different. So the following is acceptable: public string Age {get; private set;}
  • 21. Classes – Constructors public class MyClass { public MyClass() { } // rest of class definition // overloads: public MyClass() // zeroparameter constructor { // construction code } public MyClass(int number) // another overload { // construction code }
  • 22. Classes – Constructors cont. public class MyNumber { private int number; public MyNumber(int number) { this.number = number; } } This code also illustrates typical use of the this keyword to distinguish member fields from parameters of the same name. If you now try instantiating a MyNumber object using a no-parameter constructor, you will get a compilation error: MyNumber numb = new MyNumber(); // causes compilation error
  • 23. Classes – Constructors cont. We should mention that it is possible to define constructors as private or protected, so that they are invisible to code in unrelated classes too: public class MyNumber { private int number; private MyNumber(int number) // another overload { this.number = number; } } // Notes - If your class serves only as a container for some static members or properties and therefore should never be instantiated - If you want the class to only ever be instantiated by calling some static member function (this is the so-called class factory approach to object instantiation)
  • 24. Classes – Static Constructors class MyClass { static MyClass() { // initialization code } // rest of class definition }
  • 25. Classes – Static Constructors cont namespace Najah.ProCSharp.StaticConstructorSample { public class UserPreferences { public static readonly Color BackColor; static UserPreferences() { DateTime now = DateTime.Now; if (now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday) BackColor = Color.Green; else BackColor = Color.Red; } private UserPreferences() { } }}
  • 26. Classes – Static Constructors cont class MainEntryPoint { static void Main(string[] args) { Console.WriteLine(&quot;User-preferences: BackColor is: &quot; + UserPreferences.BackColor.ToString()); } } Compiling and running this code results in this output: User-preferences: BackColor is: Color [Red]
  • 27. Classes – Calling Constructors from Other Constructors class Car { private string description; private uint nWheels; public Car(string description, uint nWheels) { this.description = description; this.nWheels = nWheels; } public Car(string description) { this.description = description; this.nWheels = 4; } // etc.
  • 28. Classes – Calling Constructors from Other Constructors cont class Car { private string description; private uint nWheels; public Car(string description, uint nWheels) { this.description = description; this.nWheels = nWheels; } public Car(string description): this(description, 4) { } // etc
  • 29. Classes – Calling Constructors from Other Constructors cont class Car { private string description; private uint nWheels; public Car(string description, uint nWheels) { this.description = description; this.nWheels = nWheels; } public Car(string description): this(description, 4) { } // etc Car myCar = new Car(&quot;Proton Persona&quot;);
  • 30. Classes – readonly fields public class DocumentEditor { public static readonly uint MaxDocuments; static DocumentEditor() { MaxDocuments = DoSomethingToFindOutMaxNumber(); } }
  • 31. Classes – readonly fields cont. public class Document { public readonly DateTime CreationDate; public Document() { // Read in creation date from file. Assume result is 1 Jan 2002 // but in general this can be different for different instances // of the class CreationDate = new DateTime(2002, 1, 1); } } CreationDate and MaxDocuments in the previous code snippet are treated like any other field, except that because they are read-only, they cannot be assigned outside the constructors: void SomeMethod() { MaxDocuments = 10; // compilation error here. MaxDocuments is readonly }
  • 32. Anonymous Types Types without names : var captain = new {FirstName = “Ahmad&quot;, MiddleName = “M&quot;, LastName = “Test&quot;};
  • 33. Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com

Notes de l'éditeur

  1. using System; namespace Najah { class MainEntryPoint { static void Main() { // Try calling some static functions Console.WriteLine(&amp;quot;Pi is &amp;quot; + MathTesting.GetPi()); int x = MathTesting.GetSquareOf(5); Console.WriteLine(&amp;quot;Square of 5 is &amp;quot; + x); // Instantiate at MathTesting object MathTesting math = new MathTesting(); // this is C#&apos;s way of // instantiating a reference type // Call non-static methods math.Value = 30; Console.WriteLine( &amp;quot;Value field of math variable contains &amp;quot; + math.Value); Console.WriteLine(&amp;quot;Square of 30 is &amp;quot; + math.GetSquare()); } } // Define a class named MathTesting on which we will call a method class MathTesting { public int Value; public int GetSquare() { return Value*Value; } public static int GetSquareOf(int x) { return x*x; } public static double GetPi() { return 3.14159; // It is not a best practice but this sample for study only. } } }
  2. using System; namespace Najah { class ParametersTesting { static void SomeFunction(int[] ints, int i) { ints[0] = 100; i = 100; } public static int Main() { int i = 0; int[] ints = { 0, 1, 2, 4, 8 }; // Display the original values Console.WriteLine(&amp;quot;i = &amp;quot; + i); Console.WriteLine(&amp;quot;ints[0] = &amp;quot; + ints[0]); Console.WriteLine(&amp;quot;Calling SomeFunction...&amp;quot;); // After this method returns, ints will be changed, // but i will not SomeFunction(ints, i); Console.WriteLine(&amp;quot;i = &amp;quot; + i); Console.WriteLine(&amp;quot;ints[0] = &amp;quot; + ints[0]); return 0; } } }