1 / 56

Set # 2 Class Basics

Set # 2 Class Basics . Namespaces: Namespaces are used to logically arrange classes, structs, interfaces, enums and delegates. The namespaces in C# can be nested.

diane
Download Presentation

Set # 2 Class Basics

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. Set # 2 Class Basics Namespaces: • Namespaces are used to logically arrange classes, structs, interfaces, enums and delegates. • The namespaces in C# can be nested. • It is not possible to use any access specifies like private, public etc. with a namespace declarations. The namespaces in C# are implicitly have public access and this is not modifiable. • The .NET framework already contains number of standard namespaces like System

  2. Namespaces • The namespace elements can't be explicitly declared as private or protected • The following code doesn't compile in C#, since the class inside the namespace is declared as private. namespace test{ private class MyClass { }}

  3. Namespace declarations namespace <namespace_name> { <namespace-body> } • You can Nest namespaces: namespace Distrubution { namespace Purchasing { // Define purchasing classes } namespace Receiving { // Define receiving classes } namespace Inventory { // Define inventory classes } }

  4. Nested namespace using System; namespace Outer {namespace Inner { class MyClass { public MyClass() { Console.WriteLine("My Class"); } }} } class MyClient {public static void Main() {Outer.Inner.MyClass mc = new Outer.Inner.MyClass();} }

  5. namespace namespace N1_N2 { class A {} } namespace N3 { using N1_N2; class B: A {} // derived class }

  6. The global namespace has four members: • NamespaceY and NamespaceZ are members. • The classes ClassA and ClassB are also members. • ClassB and ClassC are ambiguous. • ClassB is ambiguous because it is defined twice in the global namespace • ClassC is defined twice in the NamespaceZ namespace.

  7. Namespace • System, is the root namespace • Equally named namespaces in different files constitute a single declaration space.

  8. “Using” Keyword: Helps the compiler locate a class that program will use pre-defined class that are organized under namespaces

  9. The .NET Type System • In C# every thing is an object. – Most object-oriented languages have two distinct types: • Primitive types or value types (int, char, struct…) • Types that can be created by users of the language (classes). • All objects (even the ones you create) implicitly are derived from a single base class : the“System.Object” Class

  10. System.Object Type methods • Public Methods of the System.Object Type – bool Equals Compares two object references at run time todetermine whether they’re the same object. If the two variables referto the same object, the return value is true. With value types, thismethod returns true if the two types are identical and have the samevalue. – string ToString Used by default to retrieve the name of the object. This method can be overridden by derived classes • Protected Methods of the System.Object Type – void Finalize Called by the runtime to allow for cleanup prior to garbage collection.

  11. Types • All types are compatible with object • -can be assigned to variables of type object • -all operations of type object are applicable to them

  12. More on Using • The “using”directive –using System.Console; //error, can’t be done. – Console is a class name. – WriteLine is a static method belongs to Console. • Also you can use aliasing –using output= System.Console; • output.WriteLine(“hi”);

  13. Contents of Classes or Structs

  14. Classes

  15. structs

  16. Structs • Declaration struct Point { public int x, y; // fields public Point (int x, int y) { this.x = x; this.y = y; } public void MoveTo (int a, int b) { x = a; y = b; }// methods } • Use Point p = new Point(3, 4);// initialize object on the stack p.MoveTo(10, 20);// method call

  17. structs using System; struct RGB { public int Red; public int Green; public int Blue; } class Test{ static void Main(string[] args) { RGB rgb; //note that we don’t have to instantiate it because rgb.Red = 0xFF; //it’s a value type. rgb.Green = 0xFF; rgb.Blue = 0xFF; Console.WriteLine(rgb.Red); //255 RGB rgb1; //Console.WriteLine(rgb1.Red); // ERROR: Use of unassigned field RGB rgb2 = new RGB();// used to initialize the fields does not allocate memory Console.WriteLine(rgb2.Red);//it initializes to 0. } }

  18. Structs • A very important limitation of structs : it’s an error to create public Complex(){} • However you can create as follows: • public Complex (double re, double im){}

  19. C# Classes • A C# class plays dual roles: • Program module: containing a list of (static) method declarations and (static) data fields • Blueprint for generating objects • It is the model or pattern from which objects are created • Supports two techniques which are essence of object-oriented programming • “data encapsulation” (for abstraction) • “inheritance” (for code reuse)

  20. User-Defined Class • A user-defined class is also called a user-defined type • class written by a programmer • A class encapsulates (wrap together) data and methods: • data members (member variables or instance variables) • methods that manipulate data members

  21. Objects • An object has: • state - descriptive characteristics • behaviors - what it can do (or be done to it) • For example, consider a coin in a computer game • The state of the coin is its current face (head or tail) • The behavior of the coin is that it can be flipped • Note the interactions between state and behaviors • the behavior of an object might change its state • the behavior of an object might depend on its state

  22. Class Declaration Class Rectangle { Point origin; public int width, height; public Rectangle() { origin = new Point(0,0); width = height = 0; } public Rectangle (Point p, int w, int h) { origin = p; width = w; height = h; } public void MoveTo (Point p) { origin = p; } } • Use Rectangle r = new Rectangle (new Point(10, 20), 5, 5); int area = r.width * r.height; r.MoveTo(new Point(3, 3));

  23. Differences Between Classes and Structs

  24. Encapsulation: Two Views of an Object • You can take one of two views of an object: • internal - the structure of its data, the algorithms used by its methods • external - the interaction of the object with other part of the world

  25. Encapsulation: An Object As a Black Box • From the external view, an object is an encapsulated entity, providing a set of specific services • These services define the interface to the object • An encapsulated object can be thought of as a black box • The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished Methods Client Data Can you think of another way to represent the state of an object of Time1?

  26. Accomplish Encapsulation: Access Modifiers • In C#, we accomplish encapsulation through the appropriate use of access modifiers • An access modifier is a C# keyword that specifies the accessibility of a method, data field, or class • We will discuss two access modifiers: public, private • We will discuss the other two modifiers (protected, internal) later • For more details, please check C# programmer’s reference (linked on schedule page)

  27. Visibility Modifiers

  28. Implementing Data Encapsulation using Properties • Use C# properties to provide access to data safely • data members should be declared private, with public properties that allow safe access to them • You access the properties of a class as if you were accessing a data field ( i.e., no () ) • Public properties allow clients to: • Get (obtain the values of) private data • get accessor: controls formatting and retrieval of data • Set (assign values to) private data • set accessor: ensure that the new value is appropriate for the data member • Although you don’t have to have both a get and a set, you must have one of the two.

  29. Property Declaration Syntax Example: class abc { private int posint; public string Posint { get { return posint;} set { if (value < 0) // code here to take error recovery action // (eg. throw an exception) else posint = value; } } // when calling in main example or some other.. abc o = new abc(); o.Posint =12; Console.Writeline(o.Posint); // prints 12 public string SomeProperty { get { return “This is the property value”; } set { // do whatever needs to be done to set the property } }

  30. Using Properties Example 2 //invoke set //invoke get

  31. Properties The set method has a hidden parameter named value that contains the new property value. A read-only property is defined by eliminating the set method. Account account=new Account(); x = account.Balance;// ok account.Balance= ...;// compilation error no set

  32. Casting Between Types • The following code works because there’s always an implied upcast:

  33. Casting Between Types, cont.. • The following is illegal because the compiler can’t provide an implicit downcast:

  34. Casting Between Types – cont. Two explicit cast are used: 1- by using (type casting) as follows this may throw a run time exception.

  35. Casting Between Types – cont. 2. We can use the “as”operator as follows. This is better because if the casting did not work the object is set to nullwithout throwing any exceptions.

  36. Access Modifiers

  37. Access Modifiers – cont. • The default access modifier is private. • Ex:

  38. Class continue: Fields and Constants int r = 6; int z = r; //error

  39. Constants vs. Read-Only Fields • Constant Fields: – A constant is a member whose value is set at compile time. – You don’t need to instantiate the class containing the constant field in order to use it, see the following example: struct point { public const long size = ((long)byte.MaxValue); } class Test { public static void Main(string[] args) { Console.WriteLine(point.size); // 255 } } • Read-Only Fields: – A field with a value that won’t be known until run time and shouldn’t be changed once it’s been initialized

  40. Example using System; using System.Net; class Workstation{ public const string HostName = “PC2289L"; // name of your computer public staticreadonly string IPAddressString; static Workstation(){ IPAddress ipAddress = Dns.Resolve(HostName).AddressList[0]; IPAddressString = ipAddress.ToString(); // initilzes address at run time } } class GetIpAddress2 { public static void Main() { Workstation workstation = new Workstation(); Console.WriteLine("The IP address for '{0}' is {1}",Workstation.HostName, Workstation.IPAddressString); // will print the ip address obtained } }// see ipadd.cs

  41. Static Members • A static method can access any static member within the class, but it can’t access an instance member. • A nonstatic method can access both static and nonstatic members. • You can use the this keyword only with nonstatic members.

  42. Static Members and InstanceMembers • By default, each member is defined as aninstance member, which means that a copy ofthat member is made for every instance of theclass. • For a static member, only one copy of themember exists. It is created when the applicationcontaining the class is loaded, and it existsthroughout the life of the application. Therefore,you can access the member even before theclass has been instantiated. struct point { public static int tes; } class Test { public static void Main(string[] args) { Console.WriteLine(point.tes); //0 } }

  43. • A static member must have a valid value. If youdid not initialize the variable, the commonlanguage runtime (CLR) will do so upon applicationstartup by using a default value of 0. Example usingSystem; classInstCount{ staticpublicintinstanceCount; publicInstCount() { instanceCount++; } //instanceCount=0; }

  44. Example, cont… class AppClass { public static void PrintInstanceCount() { Console.WriteLine(" Now there {0} " + "{1} instance{2} of class", InstCount.instanceCount == 1 ? "is" : "are", InstCount.instanceCount, InstCount.instanceCount == 1 ? "" : "s"); } public static void Main() { PrintInstanceCount(); InstCount ic; for (int i = 0; i < 2; i++) { ic = new InstCount(); Console.WriteLine("[Main] Instantiated a " + "{0} object...", ic.GetType()); PrintInstanceCount(); } } }

  45. Static Fields and Constants // public static const long siz = 76; // Error Note: We call static member using the name of class

  46. Methods

  47. Static Methods

  48. using System; enum Color{red,green,blue}; class Rectangle{ public static Color c; public int x; public static void setColor() { c = Color.blue; // x = 10; // static method can't access a non static field // solution : make an object of class Rectangle r = new Rectangle(); r.x = 10; //this.x= 2; // this illegal in static method } } class Test { public static void Main(){ Rectangle t = new Rectangle(); Console.WriteLine(t.x); // 0 Rectangle.setColor(); // static method call it by name of calss Console.WriteLine(Rectangle.c);// blue } }

  49. Method Overloading • The following lines use the WriteLine method for different data types: Console.WriteLine ("The total is:"); double total = 0; Console.WriteLine (total); • Method overloading is the process of using the same method name for multiple methods • Usually perform the same task on different data types • Example: The WriteLine method is overloaded: WriteLine (String s) WriteLine (int i) WriteLine (double d) …

  50. Method Overloading: Signature • The compiler must be able to determine which version of the method is being invoked • This is by analyzing the parameters, which form the signature of a method • The signature includes the number, type, and order of the parameters • The return type of the method is not part of the signature

More Related