1 / 31

PART I THE C# LANGUAGE

PART I THE C# LANGUAGE. Chapters 3. 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

evers
Download Presentation

PART I THE C# LANGUAGE

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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 Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  3. 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; } } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  4. 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 class PhoneCustomerStruct myCustomer2 = new PhoneCustomerStruct();// works for a struct Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  5. 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. • Fieldsare any variables associated with the class. • Syntax to access the fields: Object. FieldName PhoneCustomer Customer1 = new PhoneCustomer(); Customer1.FirstName = "Simon"; //access the field • Eventsare class members that allow an object to notify a caller whenever something noteworthy happens. Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  6. Function Members Function members are those members that provide some functionality for manipulating the data in the class. They include methods, properties, constructors, finalizers, operators, and indexers. • Methodsare functions that are associated with a particular class. • Propertiesare 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. • Finalizersare 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. Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  7. Methods Declaring Methods: • The definition of a method consists of any method modifiers, thetype 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); } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  8. Invoking Methods code snippet MathTest.cs classMathTest { staticvoid 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 = newMathTest(); // 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(); } } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  9. classMathTest { publicint value; publicint GetSquare() { return value * value; } publicstaticint GetSquareOf(int x) { return x * x; } publicstaticdouble GetPi() { return 3.14159; } } Results: Pi is 3.14159 Square of 5 is 25 Value field of math variable contains 30 Square of 30 is 900 Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  10. 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 Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  11. classParameterTest { staticvoid SomeFunction(int[] ints, int i) { ints[0] = 100; i = 100; } publicstaticint 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; } } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  12. The output of this is: i = 0 ints[0] = 0 Calling SomeFunction ... i = 0 ints [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); Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  13. 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); Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  14. 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 defined void TestMethod(int notOptionalNumber, int optionalNumber = 10) { System.Console.Write(optionalNumber + notOptionalNumber); } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  15. 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 } } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  16. Properties • The idea of a property is a method or pair of methods that is dressed to look like a field. • The getaccessor 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; } } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  17. Properties contd. • Read-Only and Write-Only Properties are created by simply omitting the setaccessor and get accessor from the property definitionrespectively. • C# does allow the set and get accessors to have differing access modifiers. • It allows a property to have a publicgetand a private or protectedset. • 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 Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  18. 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 thiskeyword to distinguish member fields from parameters of the same name. • It is possible to define constructors as private or protected. Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  19. 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 Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  20. Static Constructor Example public class UserPreferences { public static readonly Color BackColor; static UserPreferences() { DateTimenow = DateTime.Now; if (now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday) BackColor= Color.Green; else BackColor= Color.Red; } private UserPreferences() { } } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  21. Calling Constructors from Other Constructors class Car { private string description; private uintnWheels; public Car(string description, uintnWheels) { this.description= description; this.nWheels= nWheels; } public Car(string description) { this.description= description; this.nWheels= 4; } // this constructor can be written as follows public Car(string description): this(description, 4) { //Calling Constructors from Other Constructors } } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  22. readonly fields • The readonlyfield, is used on an occasion, when some variable’s value shouldn’t be changed, but the value is not known until runtime. • The readonlykeyword gives a bit more flexibility than const. public class DocumentEditor { public static readonlyuintMaxDocuments; 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. Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  23. 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}; Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  24. 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 } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  25. Struct Example struct 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); } } } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  26. 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 TheBigClasswill be created with two methods, MethodOne() and MethodTwo() //BigClassPart1.cs partial class TheBigClass { public void MethodOne(){ } } //BigClassPart2.cs partial class TheBigClass { public void MethodTwo(){ } } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  27. 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(); Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  28. 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. Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  29. 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(); } } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  30. 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; } } Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

  31. SUMMARY Reference: Professional C# 4 and .Net 4 by Bill Evjen, et al

More Related