SlideShare a Scribd company logo
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Corporation www.telerik.com
Table of Contents Defining Simple Classes Access Modifiers Using Classes and Objects Constructors Properties Static Members Structures in C#
Defining Simple Classes
Classes in OOP Classes model real-world objects and define Attributes (state, properties, fields) Behavior (methods, operations) Classes describe 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
Classes in C# Classes in C# could have following 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
Simple Class Definition public class Cat : Animal  { private string name; private string owner; public Cat(string name, string owner) { this.name = name;  this.owner = owner;  } public string Name {  get { return name; } set { name = value; } } Fields Constructor Property Begin of class definition Inherited (base) class
Simple Class Definition (2) public string Owner { get { return owner;} set { owner = value; } } public void SayMiau() { Console.WriteLine("Miauuuuuuu!"); } }  Method End of class definition
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.
Access Modifiers Public, Private, Protected, Internal
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  – accessible from the current assembly (used by default)
Defining Simple Classes Example
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" and 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
Defining Class  Dog  – Example public 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)
Defining Class  Dog  – Example  (2) public string Name {  get { return name; } set { name = value; } } public string Breed {  get { return breed; } set { breed = value; } } public void SayBau() { Console.WriteLine("{0} said: Bauuuuuu!", name); } }
Using Classes and Objects
Using Classes How to use classes? Create a new instance Access the properties of the class Invoke methods Handle events How to define classes? Create new class and define its members Create new class using some other as base class
How to Use Classes (Non-static)? Create an instance Initialize fields Manipulate instance Read / change properties Invoke methods Handle events Release occupied resources Done automatically in most cases
Task: Dog Meeting Our task is as follows: Create 3 dogs First should be named “Sharo”,   second – “Rex” and the last – left without name Add 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!
Dog Meeting – Example static void Main() { Console.WriteLine("Enter first dog's name: "); dogName = Console.ReadLine(); Console.WriteLine("Enter first dog's breed: "); dogBreed = Console.ReadLine(); // Using the Dog constructor to set name and breed Dog firstDog = new Dog(dogName, dogBreed); Dog secondDog = new Dog(); Console.WriteLine("Enter second dog's name: "); dogName = Console.ReadLine();  Console.WriteLine("Enter second dog's breed: "); dogBreed = Console.ReadLine();  // Using properties to set name and breed secondDog.Name = dogName; secondDog.Breed = dogBreed; }
Dog Meeting Live Demo
Constructors Defining and Using Class Constructors
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
Defining Constructors public class Point { private int xCoord; private int yCoord; // Simple default constructor public Point() {  xCoord = 0; yCoord = 0; } // More code ... }  Class  Point  with parameterless constructor:
Defining Constructors (2) public class Person { private string name; private int age; // Default constructor public Person() { name = null; age = 0; } // Constructor with parameters public Person(string name, int age) { this.name = name; this.age = age; } // More code ... }  As rule constructors should initialize all own class fields.
Constructors and Initialization Pay attention when using inline initialization! public class ClockAlarm { private int hours = 9; // Inline initialization private int minutes = 0; // Inline initialization // Default constructor public ClockAlarm() { } // Constructor with parameters public ClockAlarm(int hours, int minutes) { this.hours = hours;  // Invoked after the inline  this.minutes = minutes;  // initialization! } // More code ... }
Chaining Constructors Calls Reusing constructors 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 ... }
Constructors Live Demo
Properties Defining and Using Properties
The Role of Properties Expose object's data to the outside world Control how the data is manipulated Properties can be: Read-only Write-only Read and write Give good level of abstraction Make writing code easier
Defining Properties 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
Defining Properties – Example public class Point { private int xCoord; private int yCoord; public int XCoord  { get { return xCoord; } set { xCoord = value; } } public int YCoord  { get { return yCoord; } set { yCoord = value; } } // More code ... }
Dynamic Properties Properties are not obligatory bound to a class field – can be calculated dynamically public class Rectangle { private float width; private float height; // More code ... public float Area {   get { return width * height; } } }
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 };
Properties Live Demo
Static Members Static vs. Instance Members
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
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
Static Members – Example static 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)
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 } }
Static Members Live Demo
C# Structures
C# Structures What is a structure in C# A primitive data type Classes are reference types Examples:  int ,  double ,  DateTime Represented by the key word  struct Structures, like classes, have Properties, Methods, Fields, Constructors Always have a parameterless constructor This constructor cannot be removed Mostly used to store data
C# Structures – Example struct 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; } } (example continues)
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 Square(Point location, int size,  Color surfaceColor, Color borderColor) : this() { this.Location = location; this.Size = size; this.SurfaceColor = surfaceColor; this.BorderColor = borderColor; } }
Generic Classes Parameterized Classes and Methods
What are Generics? Generics allow defining 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 &quot; parameterized   types &quot; or &quot; template types &quot; Similar to the templates in C++ Similar to the generics in Java
Generics – Example public class GenericList< T >  {  public void Add( T  element) { … } } class GenericListExample {  static void Main()  {  // Declare a list of type int  GenericList<int> intList = new GenericList<int>(); // Declare a list of type string GenericList<string> stringList = new GenericList<string>(); } } T  is an unknown type, parameter of the class T  can be used in any method in the class
Generic Classes Live Demo
Summary Classes define specific structure for objects Objects are particular instances of a class and use this structure 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 classes that a primitive type
Defining Classes and Objects Questions? http://academy.telerik.com
Exercises 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 colors). Define 3 separate classes:  GSM ,  Battery  and  Display . Define several constructors for the defined classes that take different sets of arguments (the full information for the class or part of it). The unknown data fill with  null . Add a static field  NokiaN95  in the  GSM  class to hold the information about Nokia N95 device.
Exercises (2) Add a method in the class  GSM  for displaying all information about  it . Use properties to encapsulate data fields inside the  GSM ,  Battery  and  Display   classes. Write a class  GSM Test  to test  the functionality of the  GSM  class: Create several instances of the class and store them in an array. Display the information about the created  GSM  instances. Display the information about the static member  NokiaN95 .
Exercises (3) Create a class  Call  to hold a call performed through a GSM. It should contain date, time and duration. Add a property  CallsHistory  in the  GSM  class to hold a list of the performed calls. Try to use the system class  List<Call> . Add methods in the  GSM  class for adding and deleting calls to the calls history. Add a method to clear the call history. Add a method that calculates the total price of the calls in the call history. Assume the price per minute is given as parameter.
Exercises (4) 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. Remove the longest call from the history  and calculate the total price again. Finally clear the call history and print it.
Exercises (5) Write 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. Implement auto-grow functionality: when the internal array is full, create a new array of double size and move all elements to it.
Exercises (6) Define class  Fraction  that holds information about fractions: numerator and denominator. The format is &quot;numerator/denominator&quot;.  Define static method  Parse()  which is trying to parse the input string to fraction and passes the values to a constructor. Define appropriate constructors and properties. Define property  DecimalValue  which converts fraction to rounded decimal value. Write a class  FractionTest  to test  the functionality of the  Fraction  class. Parse a sequence of fractions and print their decimal values to the console.
Exercises (7) 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> ). Implement methods for adding, searching by title and author, displaying and deleting books. 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.

More Related Content

PPTX
Inheritance and its types In Java
MD SALEEM QAISAR
 
PPTX
Constructors and destructors
Vineeta Garg
 
PPTX
EASY TO LEARN INHERITANCE IN C++
Nikunj Patel
 
PDF
Chapitre 4 heritage et polymorphisme
Amir Souissi
 
PDF
From object oriented to functional domain modeling
Mario Fusco
 
PDF
Object-oriented Programming-with C#
Doncho Minkov
 
PDF
Chapitre3 tableauxcpp
Aziz Darouichi
 
PDF
Neuron Mc Culloch Pitts dan Hebb
Sherly Uda
 
Inheritance and its types In Java
MD SALEEM QAISAR
 
Constructors and destructors
Vineeta Garg
 
EASY TO LEARN INHERITANCE IN C++
Nikunj Patel
 
Chapitre 4 heritage et polymorphisme
Amir Souissi
 
From object oriented to functional domain modeling
Mario Fusco
 
Object-oriented Programming-with C#
Doncho Minkov
 
Chapitre3 tableauxcpp
Aziz Darouichi
 
Neuron Mc Culloch Pitts dan Hebb
Sherly Uda
 

What's hot (20)

PPTX
Keyboard interrupt
Tech_MX
 
PPT
Java: Objects and Object References
Tareq Hasan
 
PDF
Chapitre3TableauxEnCppV2019
Aziz Darouichi
 
PPTX
Concept of OOPS with real life examples
Neha Sharma
 
DOCX
Chapter 8 c solution
Azhar Javed
 
PDF
Files in C
Prabu U
 
PPTX
Lecture 2 C++ | Variable Scope, Operators in c++
Himanshu Kaushik
 
PDF
Hop ngu mips
mster_dang
 
PDF
Revision1schema C programming
Kho コー。イエー。イエン
 
PDF
Core java
prabhatjon
 
PPTX
Object-Oriented Programming with C#
Svetlin Nakov
 
PPTX
Running Free with the Monads
kenbot
 
PPTX
Multiple inheritance in c++
Sujan Mia
 
ODP
Function
jayesh30sikchi
 
PPTX
algorithme chapitre 1 et 2 (1).pptx
Hathat10
 
PPTX
Templates in c++
ThamizhselviKrishnam
 
PPTX
inheritance in C++
tayyaba nawaz
 
DOCX
formation excel
sarah Benmerzouk
 
PDF
[2019] Spring JPA의 사실과 오해
NHN FORWARD
 
Keyboard interrupt
Tech_MX
 
Java: Objects and Object References
Tareq Hasan
 
Chapitre3TableauxEnCppV2019
Aziz Darouichi
 
Concept of OOPS with real life examples
Neha Sharma
 
Chapter 8 c solution
Azhar Javed
 
Files in C
Prabu U
 
Lecture 2 C++ | Variable Scope, Operators in c++
Himanshu Kaushik
 
Hop ngu mips
mster_dang
 
Revision1schema C programming
Kho コー。イエー。イエン
 
Core java
prabhatjon
 
Object-Oriented Programming with C#
Svetlin Nakov
 
Running Free with the Monads
kenbot
 
Multiple inheritance in c++
Sujan Mia
 
Function
jayesh30sikchi
 
algorithme chapitre 1 et 2 (1).pptx
Hathat10
 
Templates in c++
ThamizhselviKrishnam
 
inheritance in C++
tayyaba nawaz
 
formation excel
sarah Benmerzouk
 
[2019] Spring JPA의 사실과 오해
NHN FORWARD
 
Ad

Similar to 14. Defining Classes (20)

PPT
Defining classes-and-objects-1.0
BG Java EE Course
 
PPTX
Defining classes-part-i-constructors-properties
CtOlaf
 
PPT
14 Defining classes
maznabili
 
PPTX
03 classes interfaces_principlesofoop
Vladislav Hadzhiyski
 
DOCX
OOP Lab Report.docx
ArafatSahinAfridi
 
PDF
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
PPTX
Java2
Shridhar Ramesh
 
PDF
Lecture 5
Muhammad Fayyaz
 
PPT
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
PPTX
Lesson 4
Alex Honcharuk
 
PPT
Csharp4 objects and_types
Abed Bukhari
 
PPT
Java Reflection
elliando dias
 
PPTX
constructors.pptx
Epsiba1
 
PPTX
Week9 Intro to classes and objects in Java
kjkleindorfer
 
PPTX
OOPs & C++ UNIT 3
Dr. SURBHI SAROHA
 
PPT
Advanced c#
saranuru
 
PPTX
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
PPTX
object oriented programming using java, second sem BCA,UoM
ambikavenkatesh2
 
PPTX
C++ppt. Classs and object, class and object
secondakay
 
PPTX
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
Defining classes-and-objects-1.0
BG Java EE Course
 
Defining classes-part-i-constructors-properties
CtOlaf
 
14 Defining classes
maznabili
 
03 classes interfaces_principlesofoop
Vladislav Hadzhiyski
 
OOP Lab Report.docx
ArafatSahinAfridi
 
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Lecture 5
Muhammad Fayyaz
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
Lesson 4
Alex Honcharuk
 
Csharp4 objects and_types
Abed Bukhari
 
Java Reflection
elliando dias
 
constructors.pptx
Epsiba1
 
Week9 Intro to classes and objects in Java
kjkleindorfer
 
OOPs & C++ UNIT 3
Dr. SURBHI SAROHA
 
Advanced c#
saranuru
 
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
object oriented programming using java, second sem BCA,UoM
ambikavenkatesh2
 
C++ppt. Classs and object, class and object
secondakay
 
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
Ad

More from Intro C# Book (20)

PPTX
17. Java data structures trees representation and traversal
Intro C# Book
 
PPTX
Java Problem solving
Intro C# Book
 
PPTX
21. Java High Quality Programming Code
Intro C# Book
 
PPTX
20.5 Java polymorphism
Intro C# Book
 
PPTX
20.4 Java interfaces and abstraction
Intro C# Book
 
PPTX
20.3 Java encapsulation
Intro C# Book
 
PPTX
20.2 Java inheritance
Intro C# Book
 
PPTX
20.1 Java working with abstraction
Intro C# Book
 
PPTX
19. Java data structures algorithms and complexity
Intro C# Book
 
PPTX
18. Java associative arrays
Intro C# Book
 
PPTX
16. Java stacks and queues
Intro C# Book
 
PPTX
14. Java defining classes
Intro C# Book
 
PPTX
13. Java text processing
Intro C# Book
 
PPTX
12. Java Exceptions and error handling
Intro C# Book
 
PPTX
11. Java Objects and classes
Intro C# Book
 
PPTX
09. Java Methods
Intro C# Book
 
PPTX
05. Java Loops Methods and Classes
Intro C# Book
 
PPTX
07. Java Array, Set and Maps
Intro C# Book
 
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
PPTX
02. Data Types and variables
Intro C# Book
 
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
Intro C# Book
 
20.5 Java polymorphism
Intro C# Book
 
20.4 Java interfaces and abstraction
Intro C# Book
 
20.3 Java encapsulation
Intro C# Book
 
20.2 Java inheritance
Intro C# Book
 
20.1 Java working with abstraction
Intro C# Book
 
19. Java data structures algorithms and complexity
Intro C# Book
 
18. Java associative arrays
Intro C# Book
 
16. Java stacks and queues
Intro C# Book
 
14. Java defining classes
Intro C# Book
 
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
Intro C# Book
 
09. Java Methods
Intro C# Book
 
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
02. Data Types and variables
Intro C# Book
 

Recently uploaded (20)

PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PPTX
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
This slide provides an overview Technology
mineshkharadi333
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Software Development Company | KodekX
KodekX
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Software Development Methodologies in 2025
KodekX
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 

14. Defining Classes

  • 1. Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Corporation www.telerik.com
  • 2. Table of Contents Defining Simple Classes Access Modifiers Using Classes and Objects Constructors Properties Static Members Structures in C#
  • 4. Classes in OOP Classes model real-world objects and define Attributes (state, properties, fields) Behavior (methods, operations) Classes describe 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
  • 5. Classes in C# Classes in C# could have following 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
  • 6. Simple Class Definition public class Cat : Animal { private string name; private string owner; public Cat(string name, string owner) { this.name = name; this.owner = owner; } public string Name { get { return name; } set { name = value; } } Fields Constructor Property Begin of class definition Inherited (base) class
  • 7. Simple Class Definition (2) public string Owner { get { return owner;} set { owner = value; } } public void SayMiau() { Console.WriteLine(&quot;Miauuuuuuu!&quot;); } } Method End of class definition
  • 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.
  • 9. Access Modifiers Public, 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 &quot; encapsulation &quot; 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 – accessible from the current assembly (used by default)
  • 12. 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 &quot;Balkan&quot; and its breed should be &quot;Street excellent&quot; It should be able to view and change the name and the breed of the dog The dog should be able to bark
  • 13. Defining Class Dog – Example public class Dog { private string name; private string breed; public Dog() { this.name = &quot;Balkan&quot;; this.breed = &quot;Street excellent&quot;; } public Dog(string name, string breed) { this.name = name; this.breed = breed; } (example continues)
  • 14. Defining Class Dog – Example (2) public string Name { get { return name; } set { name = value; } } public string Breed { get { return breed; } set { breed = value; } } public void SayBau() { Console.WriteLine(&quot;{0} said: Bauuuuuu!&quot;, name); } }
  • 15. Using Classes and Objects
  • 16. Using Classes How to use classes? Create a new instance Access the properties of the class Invoke methods Handle events How to define classes? Create new class and define its members Create new class using some other as base class
  • 17. How to Use Classes (Non-static)? Create an instance Initialize fields Manipulate instance Read / change properties Invoke methods Handle events Release occupied resources Done automatically in most cases
  • 18. Task: Dog Meeting Our task is as follows: Create 3 dogs First should be named “Sharo”, second – “Rex” and the last – left without name Add 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!
  • 19. Dog Meeting – Example static void Main() { Console.WriteLine(&quot;Enter first dog's name: &quot;); dogName = Console.ReadLine(); Console.WriteLine(&quot;Enter first dog's breed: &quot;); dogBreed = Console.ReadLine(); // Using the Dog constructor to set name and breed Dog firstDog = new Dog(dogName, dogBreed); Dog secondDog = new Dog(); Console.WriteLine(&quot;Enter second dog's name: &quot;); dogName = Console.ReadLine(); Console.WriteLine(&quot;Enter second dog's breed: &quot;); dogBreed = Console.ReadLine(); // Using properties to set name and breed secondDog.Name = dogName; secondDog.Breed = dogBreed; }
  • 21. Constructors Defining and Using Class Constructors
  • 22. 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. Defining Constructors public class Point { private int xCoord; private int yCoord; // Simple default constructor public Point() { xCoord = 0; yCoord = 0; } // More code ... } Class Point with parameterless constructor:
  • 24. Defining Constructors (2) public class Person { private string name; private int age; // Default constructor public Person() { name = null; age = 0; } // Constructor with parameters public Person(string name, int age) { this.name = name; this.age = age; } // More code ... } As rule constructors should initialize all own class fields.
  • 25. Constructors and Initialization Pay attention when using inline initialization! public class ClockAlarm { private int hours = 9; // Inline initialization private int minutes = 0; // Inline initialization // Default constructor public ClockAlarm() { } // Constructor with parameters public ClockAlarm(int hours, int minutes) { this.hours = hours; // Invoked after the inline this.minutes = minutes; // initialization! } // More code ... }
  • 26. Chaining Constructors Calls Reusing constructors 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 ... }
  • 28. Properties Defining and Using Properties
  • 29. The Role of Properties Expose object's data to the outside world Control how the data is manipulated Properties can be: Read-only Write-only Read and write Give good level of abstraction Make writing code easier
  • 30. Defining Properties 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
  • 31. Defining Properties – Example public class Point { private int xCoord; private int yCoord; public int XCoord { get { return xCoord; } set { xCoord = value; } } public int YCoord { get { return yCoord; } set { yCoord = value; } } // More code ... }
  • 32. Dynamic Properties Properties are not obligatory bound to a class field – can be calculated dynamically public class Rectangle { private float width; private float height; // More code ... public float Area { get { return width * height; } } }
  • 33. 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 = &quot;Steve&quot;, LastName = &quot;Balmer&quot;, UserId = 91112 };
  • 35. Static Members Static vs. Instance Members
  • 36. 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
  • 37. 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
  • 38. Static Members – Example static 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)
  • 39. 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 } }
  • 42. C# Structures What is a structure in C# A primitive data type Classes are reference types Examples: int , double , DateTime Represented by the key word struct Structures, like classes, have Properties, Methods, Fields, Constructors Always have a parameterless constructor This constructor cannot be removed Mostly used to store data
  • 43. C# Structures – Example struct 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; } } (example continues)
  • 44. 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 Square(Point location, int size, Color surfaceColor, Color borderColor) : this() { this.Location = location; this.Size = size; this.SurfaceColor = surfaceColor; this.BorderColor = borderColor; } }
  • 45. Generic Classes Parameterized Classes and Methods
  • 46. What are Generics? Generics allow defining 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 &quot; parameterized types &quot; or &quot; template types &quot; Similar to the templates in C++ Similar to the generics in Java
  • 47. Generics – Example public class GenericList< T > { public void Add( T element) { … } } class GenericListExample { static void Main() { // Declare a list of type int GenericList<int> intList = new GenericList<int>(); // Declare a list of type string GenericList<string> stringList = new GenericList<string>(); } } T is an unknown type, parameter of the class T can be used in any method in the class
  • 49. Summary Classes define specific structure for objects Objects are particular instances of a class and use this structure 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 classes that a primitive type
  • 50. Defining Classes and Objects Questions? http://academy.telerik.com
  • 51. Exercises 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 colors). Define 3 separate classes: GSM , Battery and Display . Define several constructors for the defined classes that take different sets of arguments (the full information for the class or part of it). The unknown data fill with null . Add a static field NokiaN95 in the GSM class to hold the information about Nokia N95 device.
  • 52. Exercises (2) Add a method in the class GSM for displaying all information about it . Use properties to encapsulate data fields inside the GSM , Battery and Display classes. Write a class GSM Test to test the functionality of the GSM class: Create several instances of the class and store them in an array. Display the information about the created GSM instances. Display the information about the static member NokiaN95 .
  • 53. Exercises (3) Create a class Call to hold a call performed through a GSM. It should contain date, time and duration. Add a property CallsHistory in the GSM class to hold a list of the performed calls. Try to use the system class List<Call> . Add methods in the GSM class for adding and deleting calls to the calls history. Add a method to clear the call history. Add a method that calculates the total price of the calls in the call history. Assume the price per minute is given as parameter.
  • 54. Exercises (4) 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. Remove the longest call from the history and calculate the total price again. Finally clear the call history and print it.
  • 55. Exercises (5) Write 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. Implement auto-grow functionality: when the internal array is full, create a new array of double size and move all elements to it.
  • 56. Exercises (6) Define class Fraction that holds information about fractions: numerator and denominator. The format is &quot;numerator/denominator&quot;. Define static method Parse() which is trying to parse the input string to fraction and passes the values to a constructor. Define appropriate constructors and properties. Define property DecimalValue which converts fraction to rounded decimal value. Write a class FractionTest to test the functionality of the Fraction class. Parse a sequence of fractions and print their decimal values to the console.
  • 57. Exercises (7) 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> ). Implement methods for adding, searching by title and author, displaying and deleting books. 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.

Editor's Notes

  • #3: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #4: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #5: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #7: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #8: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #9: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #12: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #13: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ## Mew = мяукам!
  • #14: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #15: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #16: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #17: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #18: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #19: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #20: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #21: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #22: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #23: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #24: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #25: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #26: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #27: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #28: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #29: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #30: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #31: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #32: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #33: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #35: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #36: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #37: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #38: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #39: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #40: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #41: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #46: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #49: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #50: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #52: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #53: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #54: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #55: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #57: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #58: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##