Your SlideShare is downloading. ×
0
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
17. Defining Classes - C# Fundamentals
Upcoming SlideShare
Loading in...5
×

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.
Text the download link to your phone
Standard text messaging rates apply

17. Defining Classes - C# Fundamentals

1,917

Published on

The presentation represents how to define classes and how to use them. …

The presentation represents how to define classes and how to use them.
What are Constructors? How to use the static members and etc.
Telerik Software Academy: http://www.academy.telerik.com
The website and all video materials are in Bulgarian.
Main topics:
Defining Simple Classes; Access Modifiers; Constructors;
Properties; Static Members; Structures in C#; Generic Classes;

C# Programming Fundamentals Course @ Telerik Academy
http://academy.telerik.com

0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,917
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
266
Comments
0
Likes
3
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Defining Classes Classes, Fields, Constructors, Methods, PropertiesSvetlin NakovManager Technical Trainerhttp://www.nakov.com/Telerik Software Academyhttp://academy.telerik.com/
  • 2. Table of Contents1. Defining Simple Classes2. Access Modifiers3. Constructors4. Properties5. Static Members6. Structures in C#7. Generic Classes 2
  • 3. Defining Simple Classes
  • 4. Classes in OOP Classes model real-world objects and define  Attributes (state, properties, fields)  Behavior (methods, operations) Classes describe the structure of objects  Objects describe particular instance of a class Properties hold information about the modeled object relevant to the problem Operations implement object behavior 4
  • 5. Classes in C# Classes in C# can have members:  Fields, constants, methods, properties, indexers, events, operators, constructors, destructors, …  Inner types (inner classes, structures, interfaces, delegates, ...) Members can have access modifiers (scope)  public, private, protected, internal Members can be  static (common) or specific for a given object 5
  • 6. Simple Class Definition Begin of class definitionpublic class Cat : Animal{ Inherited (base) class private string name; private string owner; Fields public Cat(string name, string owner) { this.name = name; this.owner = owner; Constructor } public string Name Property { get { return this.name; } set { this.name = value; } } 6
  • 7. Simple Class Definition (2) public string Owner { get { return this.owner; } set { this.owner = value; } } Method public void SayMiau() { Console.WriteLine("Miauuuuuuu!"); }} End of class definition 7
  • 8. Class Definition and Members Class definition consists of:  Class declaration  Inherited class or implemented interfaces  Fields (static or not)  Constructors (static or not)  Properties (static or not)  Methods (static or not)  Events, inner types, etc. 8
  • 9. Access ModifiersPublic, Private, Protected, Internal
  • 10. Access Modifiers Class members can have access modifiers  Used to restrict the classes able to access them  Supports the OOP principle "encapsulation" Class members can be:  public – accessible from any class  protected – accessible from the class itself and all its descendent classes  private – accessible from the class itself only  internal (default) – accessible from the current assembly, i.e. current VS project 10
  • 11. The this Keyword The keyword this inside a method points to the current instance of the class Example: class Dog { private string name; public void PrintName() { Console.WriteLine(this.name); // The same like Console.WriteLine(name); } } 11
  • 12. Defining Simple Classes Example
  • 13. Task: Define Class Dog Our task is to define a simple class that represents information about a dog  The dog should have name and breed  If there is no name or breed assigned to the dog  It should be named "Balkan"  Its breed should be "Street excellent"  It should be able to view and change the name and the breed of the dog  The dog should be able to bark 13
  • 14. Defining Class Dog – Examplepublic class Dog{ private string name; private string breed; public Dog() { this.name = "Balkan"; this.breed = "Street excellent"; } public Dog(string name, string breed) { this.name = name; this.breed = breed; } (example continues) 14
  • 15. Defining Class Dog – Example (2) public string Name { get { return this.name; } set { this.name = value; } } public string Breed { get { return this.breed; } set { this.breed = value; } } public void SayBau() { Console.WriteLine("{0} said: Bauuu!", this.name); }} 15
  • 16. Using Classes and Objects
  • 17. How to Use Classes (Non-Static)?1. Create an instance  Initialize its fields2. Manipulate the instance  Read / modify properties  Invoke methods  Handle events3. Release the occupied resources  Done automatically in most cases 17
  • 18. Task: Dog Meeting Our task is as follows:  Create 3 dogs  The first should be named “Sharo”, the second – “Rex” and the last – left without name  Put all dogs in an array  Iterate through the array elements and ask each dog to bark  Note:  Use the Dog class from the previous example! 18
  • 19. Dog Meeting – Examplestatic void Main(){ Console.WriteLine("Enter first dogs name: "); string dogName = Console.ReadLine(); Console.WriteLine("Enter first dogs breed: "); string dogBreed = Console.ReadLine(); // Use the Dog constructor to set name and breed Dog firstDog = new Dog(dogName, dogBreed); // Use Dogs parameterless constructor Dog secondDog = new Dog(); // Use properties to set name and breed Console.WriteLine("Enter second dogs name: "); secondDog.Name = Console.ReadLine(); Console.WriteLine("Enter second dogs breed: "); secondDog.Breed = Console.ReadLine(); (example continues) 19
  • 20. Dog Meeting – Example (2) // Create a Dog with default name and breed Dog thirdDog = new Dog(); // Save the dogs in an array Dog[] dogs = new Dog[] { firstDog, secondDog, thirdDog }; // Ask each of the dogs to bark foreach(Dog dog in dogs) { dog.SayBau(); }} 20
  • 21. Dog Meeting Live Demo
  • 22. ConstructorsDefining and Using Class Constructors
  • 23. What is Constructor? Constructors are special methods  Invoked when creating a new instance of an object  Used to initialize the fields of the instance Constructors has the same name as the class  Have no return type  Can have parameters  Can be private, protected, internal, public 23
  • 24. Defining Constructors Class Point with parameterless constructor: public class Point { private int xCoord; private int yCoord; // Simple parameterless constructor public Point() { xCoord = 0; yCoord = 0; } // More code ... } 24
  • 25. Defining Constructors (2)public class Person{ private string name; private int age; // Parameterless constructor public Person() { name = null; age = 0; } // Constructor with parameters public Person(string name, int age) { this.name = name; this.age = age; As rule constructors } should initialize all // More code ... own class fields.} 25
  • 26. Constructors and Initialization Pay attention when using inline initialization!public class AlarmClock{ private int hours = 9; // Inline initialization private int minutes = 0; // Inline initialization // Parameterless constructor public AlarmClock() { } // Constructor with parameters public AlarmClock(int hours, int minutes) { this.hours = hours; // Invoked after the inline this.minutes = minutes; // initialization! } // More code ...} 26
  • 27. Chaining Constructors Calls Reusing constructors (chaining) public class Point { private int xCoord; private int yCoord; public Point() : this(0,0) // Reuse constructor { } public Point(int xCoord, int yCoord) { this.xCoord = xCoord; this.yCoord = yCoord; } // More code ... } 27
  • 28. Constructors Live Demo
  • 29. PropertiesDefining and Using Properties
  • 30. The Role of Properties Expose objects data to the outside world Control how the data is manipulated  Ensure the internal object state is correct  E.g. price should always be kept positive Properties can be:  Read-only  Write-only  Read and write Make writing code easier 30
  • 31. Defining Properties Properties work as a pair of methods  Getter and setter Properties should have:  Access modifier (public, protected, etc.)  Return type  Unique name  Get and / or Set part  Can contain code processing data in specific way, e.g. apply validation 31
  • 32. Defining Properties – Examplepublic class Point{ private int xCoord; private int yCoord; public int XCoord { get { return this.xCoord; } set { this.xCoord = value; } } public int YCoord { get { return this.yCoord; } set { this.yCoord = value; } } // More code ...} 32
  • 33. Dynamic Properties Properties are not obligatory bound to a class field – can be calculated dynamically public class Rectangle { private double width; private double height; // More code ... public double Area { get { return width * height; } } } 33
  • 34. Automatic Properties Properties could be defined without an underlying field behind them  It is automatically created by the compiler class UserProfile { public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } … UserProfile profile = new UserProfile() { FirstName = "Steve", LastName = "Balmer", UserId = 91112 }; 34
  • 35. Properties Live Demo
  • 36. Keeping the Object State Correct
  • 37. Keep the Object State Correct Constructors and properties can keep the objects state correct  Can force validation when creating / modifying the objects internal state  Constructors define which properties are mandatory and which are optional  Property setters should validate the new value before saving it in the object field  Invalid values should cause an exception 37
  • 38. Keep the Object State – Examplepublic class Person{ private string name; public Person(string name) We have only one { constructor, so we this.Name = name; cannot create } person without public string Name { specifying a name. get { return this.name; } set { if (String.IsNullOrEmpty(value)) throw new ArgumentException("Invalid name!"); this.name = value; } Incorrect name }} cannot be assigned 38
  • 39. Keeping theObject State Correct Live Demo
  • 40. Static MembersStatic vs. Instance Members
  • 41. Static Members Static members are associated with a type rather than with an instance  Defined with the modifier static Static can be used for  Fields  Properties  Methods  Events  Constructors 41
  • 42. Static vs. Non-Static Static:  Associated with a type, not with an instance Non-Static:  The opposite, associated with an instance Static:  Initialized just before the type is used for the first time Non-Static:  Initialized when the constructor is called 42
  • 43. Static Members – Examplestatic class SqrtPrecalculated{ public const int MAX_VALUE = 10000; // Static field private static int[] sqrtValues; // Static constructor static SqrtPrecalculated() { sqrtValues = new int[MAX_VALUE + 1]; for (int i = 0; i < sqrtValues.Length; i++) { sqrtValues[i] = (int)Math.Sqrt(i); } } (example continues) 43
  • 44. Static Members – Example (2) // Static method public static int GetSqrt(int value) { return sqrtValues[value]; }}class SqrtTest{ static void Main() { Console.WriteLine( SqrtPrecalculated.GetSqrt(254)); // Result: 15 }} 44
  • 45. Static Members Live Demo
  • 46. C# Structures
  • 47. C# Structures What is a structure in C#?  A value data type (behaves like a primitive type)  Examples of structures: int, double, DateTime  Classes are reference types  Declared by the keyword struct  Structures, like classes, have properties, methods, fields, constructors, events, …  Always have a parameterless constructor  This constructor cannot be removed  Mostly used to store data 47
  • 48. C# Structures – Examplestruct Point{ public int X { get; set; } public int Y { get; set; }}struct Color{ public byte RedValue { get; set; } public byte GreenValue { get; set; } public byte BlueValue { get; set; }}enum Edges { Straight, Rounded } (example continues) 48
  • 49. C# Structures – Example (2)struct Square{ public Point Location { get; set; } public int Size { get; set; } public Color SurfaceColor { get; set; } public Color BorderColor { get; set; } public Edges Edges { get; set; } public Square(Point location, int size, Color surfaceColor, Color borderColor, Edges edges) : this() { this.Location = location; this.Size = size; this.SurfaceColor = surfaceColor; this.BorderColor = borderColor; this.Edges = edges; }} 49
  • 50. C# Structures Live Demo
  • 51. Generic Classes Parameterizing Classes
  • 52. What are Generics? Generics allowdefining parameterized classes that process data of unknown (generic) type  The class can be instantiated with several different particular types  Example: List<T>  List<int> / List<string> / List<Student> Generics are also known as "parameterized types" or "template types"  Similar to the templates in C++  Similar to the generics in Java 52
  • 53. Generics – Example T is an unknown type,public class GenericList<T>{ parameter of the class public void Add(T element) { … }} T can be used in anyclass GenericListExample{ method in the class static void Main() { // Declare a list of type int T can be replaced GenericList<int> intList = with int during new GenericList<int>(); the instantiation // Declare a list of type string GenericList<string> stringList = new GenericList<string>(); }} 53
  • 54. Generic Classes Live Demo
  • 55. Summary Classes define specific structure for objects  Objects are particular instances of a class Constructors are invoked when creating new class instances Properties expose the class data in safe, controlled way Static members are shared between all instances  Instance members are per object Structures are "value-type" classes Generics are parameterized classes 55
  • 56. Defining Classes and Objects курсове и уроци по програмиране, уеб дизайн – безплатно BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране – Телерик академия форум програмиране, форум уеб дизайн уроци по програмиране и уеб дизайн за ученици ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET http://academy.telerik.com/ програмиране за деца – безплатни курсове и уроци ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC безплатен SEO курс - оптимизация за търсачки алго академия – състезателно програмиране, състезаниякурсове и уроци по програмиране, книги – безплатно от Наков курс мобилни приложения с iPhone, Android, WP7, PhoneGap уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop Дончо Минков - сайт за програмиране free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране безплатен курс "Качествен програмен код" безплатен курс "Разработка на софтуер в cloud среда" C# курс, програмиране, безплатно
  • 57. Exercises1. Define a class that holds information about a mobile phone device: model, manufacturer, price, owner, battery characteristics (model, hours idle and hours talk) and display characteristics (size and number of colors). Define 3 separate classes (class GSM holding instances of the classes Battery and Display).2. Define several constructors for the defined classes that take different sets of arguments (the full information for the class or part of it). Assume that model and manufacturer are mandatory. All unknown data fill with null.3. Add an enumeration BatteryType (Li-Ion, NiMH, NiCd, …) and use it as a new field for the batteries. 57
  • 58. Exercises (2)4. Add a method in the GSM class for displaying all information about it. Try to override ToString().5. Use properties to encapsulate data fields inside the GSM, Battery and Display classes. Ensure all fields hold correct data at any given time.6. Add a static field and a property IPhone4S in the GSM class to hold the information about iPhone 4S.7. Write a class GSMTest to test the GSM class:  Create an array of few instances of the GSM class.  Display the information about the GSMs in the array.  Display the information about the static property IPhone4S. 58
  • 59. Exercises (3)8. Create a class Call to hold a call performed through a GSM. It should contain date, time, dialed phone number and duration (in seconds).9. Add a property CallHistory in the GSM class to hold a list of the performed calls. Try to use the system class List<Call>.10. Add methods in the GSM class for adding and deleting calls from the calls history. Add a method to clear the call history.11. Add a method that calculates the total price of the calls in the call history. Assume the price per minute is fixed and is given as parameter. 59
  • 60. Exercises (4)12. Write a class GSMCallHistoryTest to test the call history functionality of the GSM class.  Create an instance of the GSM class.  Add few calls.  Display the information about the calls.  Assuming that the price per minute is 0.37 calculate and print the total price of the calls in the history.  Remove the longest call from the history and calculate the total price again.  Finally clear the call history and print it. 60
  • 61. Exercises (5)13. Write a generic class GenericList<T> that keeps a list of elements of some parametric type T. Keep the elements of the list in an array with fixed capacity which is given as parameter in the class constructor. Implement methods for adding element, accessing element by index, removing element by index, inserting element at given position, clearing the list, finding element by its value and ToString(). Check all input parameters to avoid accessing elements at invalid positions.14. Implement auto-grow functionality: when the internal array is full, create a new array of double size and move all elements to it. 61
  • 62. Exercises (6)15. Define a class Fraction that holds information about fractions: numerator and denominator. The format is "numerator/denominator", e.g. 1/4. Implement the + and – operators between fractions.16. Define a static method Parse() which is trying to parse the input string (e.g. -3/4) to a fraction and passes the values to a constructor.17. Define appropriate constructors and properties. Define a property DecimalValue which converts fraction to a rounded decimal value (e.g. 0.25).18. Write a class FractionTest to test the functionality of the Fraction class. Parse a sequence of fractions and print their sum as fraction and as decimal value. 62
  • 63. Exercises (7)19. We are given a library of books. Define classes for the library and the books. The library should have name and a list of books. The books have title, author, publisher, year of publishing and ISBN. Keep the books in List<Book> (first find how to use the class System.Collections.Generic.List<T>).20. Implement methods for adding, searching by title and author, displaying and deleting books.21. Write a test class that creates a library, adds few books to it and displays them. Find all books by "Nakov", delete them and print again the library. 63
  • 64. Free Trainings @ Telerik Academy Fundamentals of C# Programming Course  csharpfundamentals.telerik.com Telerik Software Academy  academy.telerik.com Telerik Academy @ Facebook  facebook.com/TelerikAcademy Telerik Software Academy Forums  forums.academy.telerik.com

×