Csharp4 objects and_types

33
Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com

Transcript of Csharp4 objects and_types

Page 1: Csharp4 objects and_types

Abed El-Azeem Bukhari (MCPD,MCTS and MCP)el-bukhari.com

Page 2: Csharp4 objects and_types

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

Page 3: Csharp4 objects and_types

Classes and Structsclass PhoneCustomer{public const string DayOfSendingBill = "Monday";public int CustomerID;public string FirstName;public string LastName;}

struct PhoneCustomerStruct{public const string DayOfSendingBill = "Monday";public int CustomerID;public string FirstName;public string LastName;}

PhoneCustomer myCustomer = new PhoneCustomer(); // works for a classPhoneCustomerStruct myCustomer2 = new PhoneCustomerStruct();// works for a struct

Page 4: Csharp4 objects and_types

Classes - Class MembersData Members, Function Members1- Data Members: fields , constants, events• Can be static.• Fields: variables associated with class.PhoneCustomer Customer1 = new PhoneCustomer();Customer1.FirstName = “Ahmad";

• Constants : associated with the classes as other variables.public const string DayOfSendingBill = "Monday";

• Events : allow the object to tell the caller if something happen.

Eg: Like changing the value of a field or a property . It used to interact with the user.

The client can have a code called “event handler” which interact with the events

We will study events , Delegates and Lambda later at this course.

Page 5: Csharp4 objects and_types

Classes - Class Members (cont)1- Function Members:• There are : methods, properties, constructors, finalizers,

operators and indexers.• Properties : group of functions we can deal with it as same as

public fields.Properties have its own design that use : get and set classes

whit their work.• Constructors : special functions that called automatically

when we create an instance for the class . Constructors usually used for initializing the objects in the class.

It can’t have any return type !• Finalizers : same as constructors but it called when CLR see

that this object is no longer needed. Finalizers preceded by a tilde (~).

We can’t know the exactly time when the finalizers where called.

Page 6: Csharp4 objects and_types

Classes - Class Members (cont)• Operators : do operator overloading• indexers: allow to index your objects as an array or a

collection.

Page 7: Csharp4 objects and_types

Classes – Declaring a Method[modifiers] return_type MethodName([parameters]){// Method body}

Ex:public bool IsSquare(Rectangle rect){return (rect.Height == rect.Width);}

Ex: many returnspublic bool IsPositive(int value) { if (value < 0) return false; return true; }

Page 8: Csharp4 objects and_types

Classes – Invoking Methods

MathTesting.cs on Visual Studio 2010

Demo

Page 9: Csharp4 objects and_types

Classes – Passing Parameters to Methods

ParametersTesting.cs on Visual Studio 2010

Demo

Page 10: Csharp4 objects and_types

Classes – ref Parametersstatic 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 toparameters passed to methods. Any variable must be initialized before it is passed into a method, whether itis passed in by value or by reference.

Page 11: Csharp4 objects and_types

Classes – out Parametersstatic 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;}

Page 12: Csharp4 objects and_types

Classes – Named Argumentsstring FullName(string firstName, string lastName){return firstName + " " + lastName;}

The following method calls will return the same full name:

FullName(“Abed", “Bukhari");FullName(lastName: “Bukhari", firstName: “Abed");

Page 13: Csharp4 objects and_types

Classes – Optional Argumentsincorrect:

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);}

Page 14: Csharp4 objects and_types

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 refor out.

Page 15: Csharp4 objects and_types

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}}

Page 16: Csharp4 objects and_types

Classes – Properties

// mainForm is of type System.Windows.FormsmainForm.Height = 400;

To define a property in C#, you use the following syntax:public string SomeProperty{get{return "This is the property value.";}set{// do whatever needs to be done to set the property.}}

Page 17: Csharp4 objects and_types

Classes – Properties cont.

private int age;public int Age{get{return age;}set{age = value;}}

Page 18: Csharp4 objects and_types

Classes – Read-Only and Write-Only Properties

private string name;public string Name{get{return Name;}}

Page 19: Csharp4 objects and_types

Classes – Access Modifiers for Properties

public string Name{get{return _name;}private set{_name = value;}}

Page 20: Csharp4 objects and_types

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 inthe previous example we could not have checked to see if an invalid age is set. Also, both accessors must bepresent. 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;}

Page 21: Csharp4 objects and_types

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}

Page 22: Csharp4 objects and_types

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 ofthe same name. If you now try instantiating a MyNumber object using a no-parameter constructor, you willget a compilation error:MyNumber numb = new MyNumber(); // causes compilation error

Page 23: Csharp4 objects and_types

Classes – Constructors cont.

We should mention that it is possible to define constructors as private or protected, so that they are invisibleto 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)

Page 24: Csharp4 objects and_types

Classes – Static Constructors

class MyClass{static MyClass(){// initialization code}// rest of class definition}

Page 25: Csharp4 objects and_types

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;elseBackColor = Color.Red;}private UserPreferences(){}}}

Page 26: Csharp4 objects and_types

Classes – Static Constructors cont

class MainEntryPoint{static void Main(string[] args){Console.WriteLine("User-preferences: BackColor is: " +UserPreferences.BackColor.ToString());}}Compiling and running this code results in this output:User-preferences: BackColor is: Color [Red]

Page 27: Csharp4 objects and_types

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.

Page 28: Csharp4 objects and_types

Classes – Calling Constructors from Other Constructorscont

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

Page 29: Csharp4 objects and_types

Classes – Calling Constructors from Other Constructorscont

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("Proton Persona");

Page 30: Csharp4 objects and_types

Classes – readonly fields

public class DocumentEditor{public static readonly uint MaxDocuments;static DocumentEditor(){MaxDocuments = DoSomethingToFindOutMaxNumber();}}

Page 31: Csharp4 objects and_types

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 classCreationDate = new DateTime(2002, 1, 1);}}CreationDate and MaxDocuments in the previous code snippet are treated like any other field, except thatbecause they are read-only, they cannot be assigned outside the constructors:void SomeMethod(){MaxDocuments = 10; // compilation error here. MaxDocuments is readonly}

Page 32: Csharp4 objects and_types

Anonymous TypesTypes without names :

var captain = new {FirstName = “Ahmad", MiddleName = “M", LastName = “Test"};

Page 33: Csharp4 objects and_types

Thanks For Attending

Abed El-Azeem Bukhari (MCPD,MCTS and MCP)

el-bukhari.com