Defining ClassesDefining ClassesClasses, Fields, Constructors, Methods, Classes, Fields, Constructors, Methods,
PropertiesProperties
Svetlin NakovSvetlin NakovTelerik Telerik
CorporationCorporationwww.telerik.com
Table of ContentsTable of Contents
1.1. Defining Simple ClassesDefining Simple Classes
2.2. Access ModifiersAccess Modifiers
3.3. Using Classes and ObjectsUsing Classes and Objects
4.4. ConstructorsConstructors
5.5. PropertiesProperties
6.6. Static MembersStatic Members
7.7. Structures in C#Structures in C#
Defining Simple Defining Simple Classes Classes
Classes in OOPClasses in OOP Classes model real-world objects and Classes model real-world objects and
definedefine Attributes (state, properties, fields)Attributes (state, properties, fields) Behavior (methods, operations)Behavior (methods, operations)
Classes describe structure of objectsClasses describe structure of objects Objects describe particular instance of a Objects describe particular instance of a
classclass Properties hold information about the Properties hold information about the
modeled object relevant to the problemmodeled object relevant to the problem Operations implement object behaviorOperations implement object behavior
Classes in C#Classes in C# Classes in C# could have following Classes in C# could have following
members:members: FieldsFields, , constantsconstants, , methodsmethods, , propertiesproperties, ,
indexersindexers, , eventsevents, , operatorsoperators, , constructorsconstructors, , destructorsdestructors
Inner typesInner types ( (inner classesinner classes, , structuresstructures, , interfacesinterfaces, , delegatesdelegates, ...), ...)
Members can have access modifiers (scope)Members can have access modifiers (scope) publicpublic, , privateprivate, , protectedprotected, , internalinternal
Members can beMembers can be staticstatic ( (commoncommon) ) or specific for a given or specific for a given
objectobject
5
Simple Class DefinitionSimple Class Definition
public class Cat : Animal public class Cat : Animal {{ private string name;private string name; private string owner;private string owner; public Cat(string name, string owner)public Cat(string name, string owner) {{ this.name = name; this.name = name; this.owner = owner; this.owner = owner; }}
public string Namepublic string Name { { get { return name; }get { return name; } set { name = value; }set { name = value; } }}
FieldsFields
ConstrucConstructortor
ProperPropertyty
Begin of class Begin of class definitiondefinition
Inherited Inherited (base) class(base) class
Simple Class Definition Simple Class Definition (2)(2)
public string Ownerpublic string Owner {{ get { return owner;}get { return owner;} set { owner = value; }set { owner = value; } }} public void SayMiau()public void SayMiau() {{ Console.WriteLine("Miauuuuuuu!");Console.WriteLine("Miauuuuuuu!"); }}} }
MethoMethodd
End of End of class class
definitiodefinitionn
Class Definition and Class Definition and MembersMembers
Class definition consists of:Class definition consists of: Class declarationClass declaration Inherited class or implemented Inherited class or implemented
interfacesinterfaces Fields (static or not)Fields (static or not) Constructors (static or not)Constructors (static or not) Properties (static or not)Properties (static or not) Methods (static or not)Methods (static or not) Events, inner types, etc.Events, inner types, etc.
Access ModifiersAccess ModifiersPublic, Private, Protected, InternalPublic, Private, Protected, Internal
Access ModifiersAccess Modifiers Class members can have access modifiersClass members can have access modifiers
Used to restrict the classes able to access Used to restrict the classes able to access themthem
Supports the OOP principle "Supports the OOP principle "encapsulationencapsulation"" Class members can be:Class members can be:
publicpublic – accessible from any class – accessible from any class protectedprotected – accessible from the class itself – accessible from the class itself
and all its descendent classesand all its descendent classes privateprivate – accessible from the class itself – accessible from the class itself
onlyonly internalinternal – accessible from the current – accessible from the current
assembly (used by default)assembly (used by default)
Defining Simple Defining Simple ClassesClassesExampleExample
Task: Define Class Task: Define Class DogDog Our task is to define a simple class that Our task is to define a simple class that
represents information about a dogrepresents information about a dog The dog should have name and breedThe dog should have name and breed If there is no name or breed assigned If there is no name or breed assigned
to the dog, it should be named "Balkan"to the dog, it should be named "Balkan"and its breed should be "Street excellent" and its breed should be "Street excellent"
It should be able to view and change the It should be able to view and change the name and the breed of the dogname and the breed of the dog
The dog should be able to barkThe dog should be able to bark
Defining Class Defining Class DogDog – – ExampleExample
public class Dogpublic class Dog{{ private string name;private string name; private string breed;private string breed;
public Dog()public Dog() { { this.name = "Balkan";this.name = "Balkan"; this.breed = "Street excellent";this.breed = "Street excellent"; }}
public Dog(string name, string breed)public Dog(string name, string breed) { { this.name = name;this.name = name; this.breed = breed; this.breed = breed; }}
(example continues)(example continues)
Defining Class Defining Class DogDog – – ExampleExample (2) (2)
public string Namepublic string Name { { get { return name; }get { return name; } set { name = value; }set { name = value; } }} public string Breedpublic string Breed { { get { return breed; }get { return breed; } set { breed = value; }set { breed = value; } }}
public void SayBau()public void SayBau() {{ Console.WriteLine("{0} said: Bauuuuuu!", name);Console.WriteLine("{0} said: Bauuuuuu!", name); }}} }
Using Classes and Using Classes and ObjectsObjects
Using ClassesUsing Classes
How to use classes?How to use classes? Create a new instanceCreate a new instance Access the properties of the classAccess the properties of the class Invoke methodsInvoke methods Handle eventsHandle events
How to define classes?How to define classes? Create new class and define its Create new class and define its
membersmembers Create new class using some other Create new class using some other
as base classas base class
How to Use Classes How to Use Classes (Non-static)?(Non-static)?
1.1. Create an instanceCreate an instance Initialize fieldsInitialize fields
2.2. Manipulate instanceManipulate instance Read / change propertiesRead / change properties Invoke methodsInvoke methods Handle eventsHandle events
3.3. Release occupied resourcesRelease occupied resources Done automatically in most casesDone automatically in most cases
Task: Dog MeetingTask: Dog Meeting Our task is as follows:Our task is as follows:
Create 3 dogsCreate 3 dogs First should be named “Sharo”,First should be named “Sharo”,
second – “Rex” and the last – left second – “Rex” and the last – left without namewithout name
Add all dogs in an arrayAdd all dogs in an array Iterate through the array elements Iterate through the array elements
and ask each dog to barkand ask each dog to bark Note:Note:
Use the Use the DogDog class from the previous class from the previous example!example!
Dog Meeting – ExampleDog Meeting – Examplestatic void Main()static void Main(){{ Console.WriteLine("Enter first dog's name: ");Console.WriteLine("Enter first dog's name: "); dogName = Console.ReadLine();dogName = Console.ReadLine(); Console.WriteLine("Enter first dog's breed: ");Console.WriteLine("Enter first dog's breed: "); dogBreed = Console.ReadLine();dogBreed = Console.ReadLine();
// Using the Dog constructor to set name and // Using the Dog constructor to set name and breedbreed
Dog firstDog = new Dog(dogName, dogBreed);Dog firstDog = new Dog(dogName, dogBreed); Dog secondDog = new Dog();Dog secondDog = new Dog(); Console.WriteLine("Enter second dog's name: ");Console.WriteLine("Enter second dog's name: "); dogName = Console.ReadLine(); dogName = Console.ReadLine(); Console.WriteLine("Enter second dog's breed: Console.WriteLine("Enter second dog's breed: ");");
dogBreed = Console.ReadLine(); dogBreed = Console.ReadLine();
// Using properties to set name and breed// Using properties to set name and breed secondDog.Name = dogName;secondDog.Name = dogName; secondDog.Breed = dogBreed;secondDog.Breed = dogBreed;}}
Dog MeetingDog MeetingLive DemoLive Demo
ConstructorsConstructorsDefining and Using Class Defining and Using Class
ConstructorsConstructors
What is Constructor?What is Constructor? Constructors are special methodsConstructors are special methods
Invoked when creating a new instance Invoked when creating a new instance of an objectof an object
Used to initialize the fields of the Used to initialize the fields of the instanceinstance
Constructors has the same name as Constructors has the same name as the classthe class Have no return typeHave no return type Can have parametersCan have parameters Can be Can be privateprivate, , protectedprotected, , internalinternal, , publicpublic
Defining ConstructorsDefining Constructors
public class Pointpublic class Point{{ private int xCoord;private int xCoord; private int yCoord;private int yCoord;
// Simple default constructor// Simple default constructor public Point()public Point() { { xCoord = 0;xCoord = 0; yCoord = 0;yCoord = 0; }}
// More code ...// More code ...} }
Class Class PointPoint with parameterless with parameterless constructor:constructor:
Defining Constructors Defining Constructors (2)(2)
public class Personpublic class Person{{ private string name;private string name; private int age;private int age;
// Default constructor// Default constructor public Person()public Person() {{ name = null;name = null; age = 0;age = 0; }}
// Constructor with parameters// Constructor with parameters public Person(string name, int age)public Person(string name, int age) {{ this.name = name;this.name = name; this.age = age;this.age = age; }}
// More code ...// More code ...} }
As rule As rule constructors constructors
should should initialize all initialize all own class own class
fields.fields.
Constructors and Constructors and InitializationInitialization
Pay attention when using inline initialization!Pay attention when using inline initialization!
public class ClockAlarmpublic class ClockAlarm{{ private int hours = 9; // Inline initializationprivate int hours = 9; // Inline initialization private int minutes = 0; // Inline initializationprivate int minutes = 0; // Inline initialization
// Default constructor// Default constructor public ClockAlarm()public ClockAlarm() { }{ }
// Constructor with parameters// Constructor with parameters public ClockAlarm(int hours, int minutes)public ClockAlarm(int hours, int minutes) {{ this.hours = hours; // Invoked after the this.hours = hours; // Invoked after the inline inline
this.minutes = minutes; // initialization!this.minutes = minutes; // initialization! }}
// More code ...// More code ...}}
Chaining Constructors Chaining Constructors CallsCalls
Reusing constructorsReusing constructorspublic class Pointpublic class Point{{ private int xCoord;private int xCoord; private int yCoord;private int yCoord;
public Point() : this(0,0) // Reuse constructorpublic Point() : this(0,0) // Reuse constructor {{ }}
public Point(int xCoord, int yCoord)public Point(int xCoord, int yCoord) {{ this.xCoord = xCoord;this.xCoord = xCoord; this.yCoord = yCoord;this.yCoord = yCoord; }}
// More code ...// More code ...} }
ConstructorsConstructorsLive DemoLive Demo
PropertiesPropertiesDefining and Using PropertiesDefining and Using Properties
The Role of PropertiesThe Role of Properties
Expose object's data to the outside Expose object's data to the outside worldworld
Control how the data is manipulatedControl how the data is manipulated Properties can be:Properties can be:
Read-onlyRead-only Write-onlyWrite-only Read and writeRead and write
Give good level of abstractionGive good level of abstraction Make writing code easierMake writing code easier
Defining PropertiesDefining Properties
Properties should have:Properties should have: Access modifier (Access modifier (publicpublic, , protectedprotected, ,
etc.)etc.) Return typeReturn type Unique nameUnique name GetGet and / or and / or SetSet part part Can contain code processing data Can contain code processing data
in specific wayin specific way
Defining Properties – Defining Properties – ExampleExample
public class Pointpublic class Point{{ private int xCoord;private int xCoord; private int yCoord;private int yCoord;
public int XCoord public int XCoord {{ get { return xCoord; }get { return xCoord; } set { xCoord = value; }set { xCoord = value; } }}
public int YCoord public int YCoord {{ get { return yCoord; }get { return yCoord; } set { yCoord = value; }set { yCoord = value; } }}
// More code ...// More code ...} }
Dynamic PropertiesDynamic Properties Properties are not obligatory bound to a Properties are not obligatory bound to a
class field – can be calculated dynamicallyclass field – can be calculated dynamically
public class Rectanglepublic class Rectangle{{ private float width;private float width; private float height;private float height;
// More code ...// More code ...
public float Areapublic float Area {{ getget {{ return width * height;return width * height; }} }}}}
Automatic PropertiesAutomatic Properties
Properties could be defined Properties could be defined without an underlying field behind without an underlying field behind themthem It is automatically created by the It is automatically created by the
compilercompiler
33
class UserProfileclass UserProfile{{ public int UserId { get; set; }public int UserId { get; set; } public string FirstName { get; set; }public string FirstName { get; set; } public string LastName { get; set; }public string LastName { get; set; }}}……UserProfile profile = new UserProfile() {UserProfile profile = new UserProfile() { FirstName = "Steve",FirstName = "Steve", LastName = "Balmer",LastName = "Balmer", UserId = 91112 };UserId = 91112 };
PropertiesPropertiesLive DemoLive Demo
Static MembersStatic MembersStatic vs. Instance Static vs. Instance MembersMembers
Static MembersStatic Members
Static members are associated Static members are associated with a type rather than with an with a type rather than with an instanceinstance Defined with the modifier Defined with the modifier staticstatic
Static can be used forStatic can be used for FieldsFields PropertiesProperties MethodsMethods EventsEvents ConstructorsConstructors
Static vs. Non-StaticStatic vs. Non-Static StaticStatic: :
Associated with a type, not with an Associated with a type, not with an instanceinstance
Non-StaticNon-Static: : The opposite, associated with an The opposite, associated with an
instanceinstance StaticStatic: :
Initialized just before the type is used Initialized just before the type is used for the first timefor the first time
Non-StaticNon-Static:: Initialized when the constructor is calledInitialized when the constructor is called
Static Members – Static Members – ExampleExample
static class SqrtPrecalculatedstatic class SqrtPrecalculated{{ public const int MAX_VALUE = 10000;public const int MAX_VALUE = 10000; // Static field // Static field private static int[] sqrtValues; private static int[] sqrtValues;
// Static constructor // Static constructor static SqrtPrecalculated()static SqrtPrecalculated() {{ sqrtValues = new int[MAX_VALUE + 1];sqrtValues = new int[MAX_VALUE + 1]; for (int i = 0; i < sqrtValues.Length; i++)for (int i = 0; i < sqrtValues.Length; i++) {{ sqrtValues[i] = (int)Math.Sqrt(i);sqrtValues[i] = (int)Math.Sqrt(i); }} }}
(example continues)(example continues)
Static Members – Static Members – Example (2)Example (2)
// Static method // Static method public static int GetSqrt(int value)public static int GetSqrt(int value) {{ return sqrtValues[value];return sqrtValues[value]; }}}}
class SqrtTestclass SqrtTest{{ static void Main()static void Main() {{
Console.WriteLine(SqrtPrecalculated.GetSqrt(254));Console.WriteLine(SqrtPrecalculated.GetSqrt(254)); // Result: 15// Result: 15 }}}}
Static MembersStatic MembersLive DemoLive Demo
C# StructuresC# Structures
C# StructuresC# Structures What is a structure in C#What is a structure in C#
A primitive data typeA primitive data type Classes are reference typesClasses are reference types
Examples: Examples: intint, , doubledouble, , DateTimeDateTime
Represented by the key word Represented by the key word structstruct Structures, like classes, have Structures, like classes, have
Properties, Methods, Fields, Properties, Methods, Fields, ConstructorsConstructors
Always have a parameterless Always have a parameterless constructorconstructor This constructor cannot be removedThis constructor cannot be removed
Mostly used to store dataMostly used to store data
C# Structures – C# Structures – ExampleExample
struct Pointstruct Point{{ public int X { get; set; }public int X { get; set; } public int Y { get; set; }public int Y { get; set; }}}
struct Colorstruct Color{{ public byte RedValue { get; set; }public byte RedValue { get; set; } public byte GreenValue { get; set; }public byte GreenValue { get; set; } public byte BlueValue { get; set; }public byte BlueValue { get; set; }}}
(example continues)(example continues)
C# Structures – C# Structures – Example (2)Example (2)
struct Squarestruct Square{{ public Point Location { get; set; }public Point Location { get; set; } public int Size { get; set; }public int Size { get; set; } public Color SurfaceColor { get; set; }public Color SurfaceColor { get; set; } public Color BorderColor { get; set; }public Color BorderColor { get; set; } public Square(Point location, int size, public Square(Point location, int size, Color surfaceColor, Color borderColor) : this()Color surfaceColor, Color borderColor) : this() {{ this.Location = location;this.Location = location; this.Size = size;this.Size = size; this.SurfaceColor = surfaceColor;this.SurfaceColor = surfaceColor; this.BorderColor = borderColor;this.BorderColor = borderColor; }}}}
Generic Generic ClassesClassesParameterized Classes and Parameterized Classes and
MethodsMethods
What are Generics?What are Generics? Generics allow defining parameterized Generics allow defining parameterized
classes that process data of unknown classes that process data of unknown (generic) type(generic) type The class can be instantiated with The class can be instantiated with
several different particular typesseveral different particular types Example: Example: List<T>List<T> List<int>List<int> / / List<string>List<string> / / List<Student>List<Student>
Generics are also known as Generics are also known as ""parameterizedparameterized typestypes" or "" or "template template typestypes"" Similar to the templates in C++Similar to the templates in C++ Similar to the generics in JavaSimilar to the generics in Java
Generics – ExampleGenerics – Example
public class GenericList<public class GenericList<TT> > { { public void Add(public void Add(TT element) { … } element) { … }}}
class GenericListExampleclass GenericListExample{ { static void Main() static void Main() { { // Declare a list of type int // Declare a list of type int GenericList<int> intList =GenericList<int> intList = new GenericList<int>();new GenericList<int>();
// Declare a list of type string// Declare a list of type string GenericList<string> stringList =GenericList<string> stringList = new GenericList<string>();new GenericList<string>(); }}}}
TT is an unknown is an unknown type, parameter type, parameter
of the classof the class
TT can be used in can be used in any method in any method in
the classthe class
Generic ClassesGeneric ClassesLive DemoLive Demo
SummarySummary Classes define specific structure for Classes define specific structure for
objectsobjects Objects are particular instances of a Objects are particular instances of a
class and use this structureclass and use this structure Constructors are invoked when Constructors are invoked when
creating new class instancescreating new class instances Properties expose the class data in Properties expose the class data in
safe, controlled waysafe, controlled way Static members are shared between Static members are shared between
all instancesall instances Instance members are per objectInstance members are per object
Structures are classes that a primitive Structures are classes that a primitive typetype
Defining Classes and Defining Classes and ObjectsObjects
Questions?
http://academy.telerik.com
ExercisesExercises1.1. Define a class that holds information about a Define a class that holds information about a
mobile phone device: model, manufacturer, mobile phone device: model, manufacturer, price, owner, battery characteristics (model, price, owner, battery characteristics (model, hours idle and hours talk) and display hours idle and hours talk) and display characteristics (size and colors). Define 3 characteristics (size and colors). Define 3 separate classes: separate classes: GSMGSM, , BatteryBattery and and DisplayDisplay..
2.2. Define several constructors for the defined Define several constructors for the defined classes that take different sets of arguments classes that take different sets of arguments (the full information for the class or part of (the full information for the class or part of it). The unknown data fill with it). The unknown data fill with nullnull..
3.3. Add a static field Add a static field NokiaN95NokiaN95 in the in the GSMGSM class to class to hold the information about Nokia N95 device.hold the information about Nokia N95 device.
Exercises (2)Exercises (2)4.4. Add a method in the class Add a method in the class GSMGSM for for
displaying all information about displaying all information about itit..
5.5. Use properties to encapsulate data fields Use properties to encapsulate data fields inside the inside the GSMGSM, , BatteryBattery and and DisplayDisplay classes.classes.
6.6. Write a class Write a class GSMGSMTestTest to test to test the the functionality of the functionality of the GSMGSM class: class:
4.4.Create several instances of the class and Create several instances of the class and store them in an array.store them in an array.
5.5.Display the information about the Display the information about the created created GSMGSM instances. instances.
6.6.Display the information about the static Display the information about the static member member NokiaN95NokiaN95..
Exercises (3)Exercises (3)
7.7. Create a class Create a class CallCall to hold a call performed to hold a call performed through a GSM. It should contain date, through a GSM. It should contain date, time and duration.time and duration.
8.8. Add a property Add a property CallsHistoryCallsHistory in the in the GSMGSM class to hold a list of the performed calls. class to hold a list of the performed calls. Try to use the system class Try to use the system class List<Call>List<Call>..
9.9. Add methods in the Add methods in the GSMGSM class for adding class for adding and deleting calls to the calls history. Add and deleting calls to the calls history. Add a method to clear the call history.a method to clear the call history.
10.10. Add a method that calculates the total Add a method that calculates the total price of the calls in the call history. Assume price of the calls in the call history. Assume the price per minute is given as parameter.the price per minute is given as parameter.
Exercises (4)Exercises (4)
11.11. Write a class Write a class GSMCallHistoryTestGSMCallHistoryTest to test to test the call history functionality of the the call history functionality of the GSMGSM class.class.
Create an instance of the Create an instance of the GSMGSM class. class.
Add few calls.Add few calls.
Display the information about the calls.Display the information about the calls.
Assuming that the price per minute is 0.37 Assuming that the price per minute is 0.37 calculate and print the total price of the calculate and print the total price of the calls.calls.
Remove the longest call from the history Remove the longest call from the history and calculate the total price again.and calculate the total price again.
Finally clear the call history and print it.Finally clear the call history and print it.
Exercises (5)Exercises (5)
55
12.12. Write generic class Write generic class GenericList<T>GenericList<T> that that keeps a list of elements of some keeps a list of elements of some parametric type parametric type TT. Keep the elements . Keep the elements of the list in an array with fixed of the list in an array with fixed capacity which is given as parameter in capacity which is given as parameter in the class constructor. Implement the class constructor. Implement methodsmethods for adding element, accessing for adding element, accessing element by index, removing element by element by index, removing element by index, inserting element at given index, inserting element at given position, clearing the list, finding position, clearing the list, finding element by its value and element by its value and ToString()ToString(). . Check all input parameters to avoid Check all input parameters to avoid accessing elements at invalid accessing elements at invalid positions.positions.
13.13. Implement auto-grow functionality: Implement auto-grow functionality: when the internal array is full, create a when the internal array is full, create a new array of double size and move all new array of double size and move all elements to it.elements to it.
Exercises (6)Exercises (6)14.14.Define class Define class FractionFraction that holds information that holds information
about fractions: numerator and denominator. about fractions: numerator and denominator. The format is "numerator/denominator". The format is "numerator/denominator".
15.15.Define static method Define static method Parse()Parse() which is trying which is trying to parse the input string to fraction and to parse the input string to fraction and passes the values to a constructor.passes the values to a constructor.
16.16.Define appropriate constructors and Define appropriate constructors and properties. Define property properties. Define property DecimalValueDecimalValue which converts fraction to rounded decimal which converts fraction to rounded decimal value.value.
17.17.Write a class Write a class FractionTestFractionTest to test to test the the functionality of the functionality of the FractionFraction class. Parse a class. Parse a sequence of fractions and print their decimal sequence of fractions and print their decimal values to the console.values to the console.
Exercises (7)Exercises (7)
18.18. We are given a library of books. Define classes We are given a library of books. Define classes for the library and the books. The library for the library and the books. The library should have name and a list of books. The should have name and a list of books. The books have title, author, publisher, year of books have title, author, publisher, year of publishing and ISBN. Keep the books in publishing and ISBN. Keep the books in List<Book> (first find how to use the class List<Book> (first find how to use the class System.Collections.Generic.List<T>System.Collections.Generic.List<T>).).
19.19. Implement methods for adding, searching by Implement methods for adding, searching by title and author, displaying and deleting title and author, displaying and deleting books.books.
20.20. Write a test class that creates a library, adds Write a test class that creates a library, adds few books to it and displays them. Find all few books to it and displays them. Find all books by Nakov, delete them and print again books by Nakov, delete them and print again the library.the library.
Top Related