0
Upcoming SlideShare
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Standard text messaging rates apply

# Csharp4 objects and_types

989

Published on

Published in: Technology
1 Like
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total Views
989
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
123
0
Likes
1
Embeds 0
No embeds

No notes for slide
• 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. } } }
• 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; } } }
• ### Transcript

• 1. Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com
• 2. Objects &amp; 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. Classes and Structs <ul><li>class PhoneCustomer </li></ul><ul><li>{ </li></ul><ul><li>public const string DayOfSendingBill = &amp;quot;Monday&amp;quot;; </li></ul><ul><li>public int CustomerID; </li></ul><ul><li>public string FirstName; </li></ul><ul><li>public string LastName; </li></ul><ul><li>} </li></ul>struct PhoneCustomerStruct { public const string DayOfSendingBill = &amp;quot;Monday&amp;quot;; 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
• 4. Classes - Class Members <ul><li>Data Members, Function Members </li></ul><ul><li>1- Data Members : </li></ul><ul><li>fields , constants, events </li></ul><ul><li>Can be static. </li></ul><ul><li>Fields: variables associated with class. </li></ul><ul><li>PhoneCustomer Customer1 = new PhoneCustomer(); </li></ul><ul><li>Customer1.FirstName = “Ahmad&amp;quot;; </li></ul><ul><li>Constants : associated with the classes as other variables. </li></ul><ul><li>public const string DayOfSendingBill = &amp;quot;Monday&amp;quot;; </li></ul><ul><li>Events : allow the object to tell the caller if something happen. </li></ul><ul><li>Eg: Like changing the value of a field or a property . It used to interact with the user. </li></ul><ul><li>The client can have a code called “event handler” which interact with the events </li></ul><ul><li>We will study events , Delegates and Lambda later at this course. </li></ul>
• 5. Classes - Class Members (cont) <ul><li>1- Function Members : </li></ul><ul><li>There are : methods, properties, constructors, finalizers, operators and indexers. </li></ul><ul><li>Properties : group of functions we can deal with it as same as public fields. </li></ul><ul><li>Properties have its own design that use : get and set classes whit their work. </li></ul><ul><li>Constructors : special functions that called automatically when we create an instance for the class . Constructors usually used for initializing the objects in the class. </li></ul><ul><li>It can’t have any return type ! </li></ul><ul><li>Finalizers : same as constructors but it called when CLR see that this object is no longer needed. Finalizers preceded by a tilde (~). </li></ul><ul><li>We can’t know the exactly time when the finalizers where called. </li></ul>
• 6. Classes - Class Members (cont) <ul><li>Operators : do operator overloading </li></ul><ul><li>indexers: allow to index your objects as an array or a collection. </li></ul>
• 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 &lt; 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 + &amp;quot; &amp;quot; + lastName; } The following method calls will return the same full name: FullName(“Abed&amp;quot;, “Bukhari&amp;quot;); FullName(lastName: “Bukhari&amp;quot;, firstName: “Abed&amp;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 &amp;quot;This is the property value.&amp;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(&amp;quot;User-preferences: BackColor is: &amp;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(&amp;quot;Proton Persona&amp;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&amp;quot;, MiddleName = “M&amp;quot;, LastName = “Test&amp;quot;};
• 33. Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com