PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

31
PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al 1

Transcript of PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Page 1: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

PART I THE C# LANGUAGEChapters 3

1

Page 2: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Chapter 3- Objects and Types• 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

2

Page 3: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Classes And Structs• Classes and structs are essentially templates from which objects can be

created.

• Each object contains data and has methods to manipulate and access that

data.

• The class defines what data and functionality each particular object (called

an instance ) of that class can contain.

• Examples: Class Struct class PhoneCustomer struct PhoneCustomerStruct{ {public int CustomerID; public int CustomerID;public string FirstName; public string FirstName;public string LastName; public string LastName;} } 3

Page 4: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Classes and Structs• Structs differ from classes in the way that they are stored in memory and

accessed

• Structs don’t support inheritance, and are used for smaller data types for

performance reasons

• Instantiation of a class and Struct

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

4

Page 5: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Classes• The data and functions within a class are known as the class’s members.

• Classes can contain nested types (such as other classes).

• Accessibility to the members can be public, protected, internal protected,

private, or internal.

Data Members

• Data members are those members that contain the data for the class —

fields, constants, and events.

• Data members can be static. A class member is always an instance

member unless it is explicitly declared as static.

• Fields are any variables associated with the class.• Syntax to access the fields: Object. FieldName

PhoneCustomer Customer1 = new PhoneCustomer();Customer1.FirstName = "Simon"; //access the field

• Events are class members that allow an object to notify a caller whenever something noteworthy happens.

5

Page 6: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Function MembersFunction members are those members that provide some functionality for

manipulating the data in the class. They include methods, properties,

constructors, finalizers, operators, and indexers.

• Methods are functions that are associated with a particular class.

• Properties are sets of functions that can be accessed from the client in a

similar way to the public fields of the class.

• Constructors are special functions that are called automatically when an

object is instantiated.

• Finalizers are similar to constructors but are called when the CLR detects that

an object is no longer needed.

• Operators, at their simplest, are actions such as + or –. Operator overloading

is also possible with C#.

• Indexers allow your objects to be indexed in the same way as an array or

collection.6

Page 7: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

MethodsDeclaring Methods:

• The definition of a method consists of any method modifiers, the type of the return value, followed by the name of the method, followed by a list of input arguments enclosed in parentheses, followed by the body of the method enclosed in curly braces.

[modifiers] return_type MethodName([parameters])

{

// Method body

}

• Each parameter consists of the name of the type of the parameter, and the name by which it can be referenced in the body of the method.

public bool IsSquare(Rectangle rect)

{

return (rect.Height == rect.Width);

}

7

Page 8: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Invoking Methods code snippet MathTest.cs

class MathTest { static void Main(string[] args) { // Try calling some static functions. Console.WriteLine("Pi is " + MathTest.GetPi()); int x = MathTest.GetSquareOf(5); Console.WriteLine("Square of 5 is " + x); // Instantiate at MathTest object MathTest math = new MathTest(); // this is C#'s way of // instantiating a reference type // Call nonstatic methods math.value = 30; Console.WriteLine( "Value field of math variable contains " + math.value); Console.WriteLine("Square of 30 is " + math.GetSquare()); Console.ReadLine(); } }

8

Page 9: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

class MathTest { 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; } }Results:Pi is 3.14159Square of 5 is 25Value field of math variable contains 30Square of 30 is 900

9

Page 10: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Passing Parameters to Methods

• parameters can be passed into methods by reference or by value.

• When a variable is passed by reference, the called method gets the actual

variable — so any changes made to the variable inside the method

persist when the method exits.

• when a variable is passed by value, the called method gets an identical

copy of the variable — which means any changes made are lost when the

method exits.

• In C#, all parameters are passed by value unless specified.

• It also requires that variables be initialized with a starting value before they are referenced

• Example: code snippet ParameterTest.cs 10

Page 11: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

class ParameterTest { 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("i = " + i); Console.WriteLine("ints[0] = " + ints[0]); Console.WriteLine("Calling SomeFunction."); // After this method returns, ints will be changed, // but i will not. SomeFunction(ints, i); Console.WriteLine("i = " + i); Console.WriteLine("ints[0] = " + ints[0]); Console.ReadLine(); return 0; } }

11

Page 12: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

The output of this is:i = 0ints[0] = 0Calling SomeFunction ...i = 0ints[0] = 100

• The value of i remains unchanged, but the value changed in ints is also changed in the original array.

• Strings don’t display the typical reference-type behavior as they are immutable.

ref Parameters• To force value parameters to be passed by reference, the ref keyword is

used.static void SomeFunction(int[] ints, ref int i){ints[0] = 100;i = 100; // The change to i will persist after SomeFunction() exits.}

To invoke: SomeFunction(ints, ref i);

12

Page 13: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

out Parameters• The out parameter enables the functions to output more than one value

from a single routine by assigning the output values to variables that have been passed to the method by reference.

• When a method’s input argument is prefixed with out, that method can be passed a variable that has not been initialized.

static void SomeFunction(out int i){i = 100;}To invoke:int i; // note how i is declared but not initialized.SomeFunction(out i);

13

Page 14: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Named Arguments• Typically, parameters need to be passed into a method in the same order that

they are defined.

• Named arguments allows to pass in parameters in any order. string FullName(string firstName, string lastName)

{ return firstName + " " + lastName;

}

The following method calls will return the same full name:FullName("John", "Doe");

FullName(lastName: "Doe", firstName: "John");

Optional Arguments• Parameters can also be optional.

• A default value for optional parameters is required.

• Optional parameter(s) must be the last ones definedvoid TestMethod(int notOptionalNumber, int optionalNumber = 10)

{

System.Console.Write(optionalNumber + notOptionalNumber);

}

14

Page 15: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Method Overloading• Method overloading - several versions of the method that have different

signatures.

• Different signatures mean the same name, but a different number of

parameters and/or different parameter data types.

• Method overloading carries with it the potential for subtle runtime bugs if

the wrong overload is called. It is not sufficient for two methods to differ

only in their return type or only by virtue of a parameter having been

declared as ref or out.class ResultDisplayer

{

void DisplayResult(string result)

{ // implementation

}

void DisplayResult(int result)

{ // implementation

}

}

15

Page 16: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Properties• The idea of a property is a method or pair of methods that is dressed to

look like a field.• The get accessor takes no parameters and must return the same type as

the declared property.• The compiler assumes that the set accessor takes one parameter, which

is of the same type and is referred to as value.private int age;public int Age{ get

{return age;}set{age = value;}

}16

Page 17: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Properties contd.• Read-Only and Write-Only Properties are created by simply omitting

the set accessor and get accessor from the property definition respectively.

• C# does allow the set and get accessors to have differing access modifiers.

• It allows a property to have a public get and a private or protected set.• If there isn’t going to be any logic in the properties set and get , then auto

- implemented properties can be used. public string Age {get; set;}

• The declaration private int age; is not needed.• Auto - implemented properties implement the backing member variable

automatically.public string Age {get; private set;}// also allowed

17

Page 18: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Constructors• A method that has the same name as the containing class and that does not

have any return type.public class MyClass

{ public MyClass(){ }

// rest of class definition

}

• It’s not necessary to provide a constructor, the compiler will make up a default one that initializes all the member fields by zeroing them out.

• Constructors follow the same rules for overloading as other methods.

• If any constructors that take parameters is provided, the compiler will not automatically supply a default one.

• The this keyword to distinguish member fields from parameters of the same name.

• It is possible to define constructors as private or protected.18

Page 19: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Static Constructor• It is also possible to write a static no-parameter constructor for a class.

• As opposed to the constructors written so far, which are instance constructors that are executed whenever an object of that class is created, Static constructors are executed only once.

• One reason for writing a static constructor is if a class has some static fields or properties that need to be initialized from an external source before the class is first used.

• The static constructor does not have any access modifiers.• It’s never called by any other C# code, but always by the .NET runtime

when the class is loaded.• It is possible to have a static constructor and a zero-parameter instance

constructor defined in the same class

19

Page 20: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Static Constructor Examplepublic 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(){}

} 20

Page 21: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

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;} // this constructor can be written as followspublic Car(string description): this(description, 4){ //Calling Constructors from Other Constructors}

} 21

Page 22: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

readonly fields• The readonly field, is used on an occasion, when some variable’s value

shouldn’t be changed, but the value is not known until runtime.• The readonly keyword gives a bit more flexibility than const.public class DocumentEditor{

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

}

• It is not required to assign a value to a readonly field in a constructor, a default value of its datatype is assigned automatically. That applies to both static and instance readonly fields.

22

Page 23: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Anonymous Types• The var keyword, when used with the new keyword, anonymous types can

be created.• If an object that contains a person’s first, middle, and last name is to be

created anonymously, the declaration would look like this:var doctor = new {FirstName = "Leonard", MiddleName = "", LastName = "McCoy"};

var captain = new {FirstName = "James", MiddleName = "T", LastName = "Kirk"};[or]var captain = new {person.FirstName, person.MiddleName, person.LastName};

23

Page 24: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Structs• When only a small data structure is needed, for performance reasons a

struct is probably preferred to a class.

• Structs are value types, not reference types.• Structs do not support inheritance.• The compiler always supplies a default no-parameter constructor for

structs, which are not permitted to be replaced.• With a struct, the specification on how the fields are to be laid out in

memory can be done by the programmer.

struct Dimensions

{

public double Length = 1; // error. Initial values not allowed

public double Width = 2; // error. Initial values not allowed

}

24

Page 25: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Struct Examplestruct Dimensions{

public double Length;public double Width;public Dimensions(double length, double width){ Length=length;

Width=width;}public double Diagonal{

get{

return Math.Sqrt(Length*Length + Width*Width);}

}}

25

Page 26: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Partial Classes• The partial keyword allows the class, struct, method or interface to span

across multiple files.

• Typically, a class will reside entirely in a single file, but when it resides in multiple files then a partial class comes into play.

• For example, the class TheBigClass resides in two separate source files, BigClassPart1.cs and BigClassPart2.cs

• When the project that these two source files are part of is compiled, a single type called TheBigClass will be created with two methods, MethodOne() and MethodTwo()

//BigClassPart1.cspartial class TheBigClass{ public void MethodOne(){ }}//BigClassPart2.cspartial class TheBigClass{ public void MethodTwo(){ }}

26

Page 27: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Static Classes• If a class contains nothing but static methods and properties, the class

itself can become static.• It is the same as creating a class with a private static constructor.• An instance of the class can never be created and if created a compiler

error occurs.static class StaticUtilities{

public static void HelperMethod(){}

}

To call the method: StaticUtilities.HelperMethod();

27

Page 28: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

The Object Class• All .NET classes are ultimately derived from System.Object

System.Object Methods• ToString() - A fairly basic, quick-and-easy string representation which

displays the contents of an object.• GetHashCode() – If objects are placed in a data structure known as a

map(Hash table), this method is used to determine where to place an object in the structure.

• Equals() (both versions) and ReferenceEquals() - Aimed at comparing the equality of objects.

• Finalize() - is called when a reference object is garbage collected to clean up resources. Hence the object is ignored by the garbage collector.

• GetType() - Returns an instance of a class derived from System.Type so this object can provide information about the class of which the object is a member, including base type, methods, properties, and so on.

• MemberwiseClone() - simply makes a copy of the object and returns a reference (or in the case of a value type, a boxed reference) to the copy. 28

Page 29: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

The Tostring() method• It provides the most convenient way to get a quick string representation of an

object.• Object.ToString() is actually declared as virtual.Public Class MainEntryPoint{

static void Main(string[] args){ Money cash1 = new Money();

cash1.Amount = 40M;Console.WriteLine("cash1.ToString() returns: " + cash1.ToString());Console.ReadLine();

}}public class Money{ private decimal amount;

public decimal Amount{ get{ return amount; }

set{ amount = value; }}public override string ToString(){ return "$" + Amount.ToString(); }

}

29

Page 30: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

Extension Methods• There are many ways to extend a class, like inheritance.• Extension methods can help by allowing us to change a class without

requiring the source code for the class.• Extension methods are static methods that can appear to be part of a

class without actually being in the source code for the class.• For an extension method, the first parameter is the type that is being

extended preceded by the this keyword.• In the extension method, all the public methods and properties of the

type being extended are accessible• If the extension method has the same name as a method in the class, the

extension method will never be called. Any instance methods already in the class take precedence.

• Example:public static class MoneyExtension{ public static void AddToAmount(this Money money, decimal amountToAdd) { money.Amount += amountToAdd; }}

30

Page 31: PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.

Ref

eren

ce: P

rofe

ssio

nal C

# 4

and

.N

et 4

by

Bill

Evj

en, e

t al

SUMMARY

31