Classes - Part 1
Telerik Academy Alpha

 

 Table of contents

What are classes?

 What are classes?

  • Classes are used to model real-world objects in programming

    • State (fields, properties)

    • Behavior (methods, operations)

  • Classes describe the structure of object

    • Objects are particular instance of a class

// class
public class Person
{
    // Model the person
}

// object (use the class for creating instance)
Person person = new Person();

 What are classes?

class Person
{
    // State
    public string Name { get; set; }

    // Behavior
    public void Speak()
    {
        Console.WriteLine($"Hello I'm {this.Name}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();
        person.Name = "John";
        person.Speak();  // Hello, I'm John
    }
}

 What are classes?

 What are classes?

Definition and members

Class Definition

 Class definition

  • Class definition consists of:

    • Inherited class or implemented interface

    • Fields (static or not)
    • Constructors (static or not)
    • Properties (static or not)
    • Methods (static or not)
    • Events, inner types, etc.

 Class definition

  • 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 instance (specific for a given object)

Fields

 Fields

  • Fields are data members defined inside a class

    • internal object state

    • could have any access modifier

      • but they must be always private

class Person
{
    private string firstName;
    private string lastName;
    private int age;
}

 Constant fields

  • Two types

    • const ​- compile-time 

      • Replaced during compilation

      • Contain only values known at compile time

    • readonly - runtime 

      • Assigned once at object creation

      • Can contain values, calculated at runtime

 Constant fields - live demo

Access Modifiers

 Access modifiers

  • Class members can have access modifiers
    • Restrict the access to them from outer sources
    • 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. the current VS project

 Access modifiers - live demo

Constructors and

'this' keyword

 The this keyword

  • The keyword this inside a method points to the current instance of the class

 Constructor

  • Constructors are kind of special methods
    • Invoked at the time of 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

 Constructor

  • Classes could have multiple constructors
  • If you don't provide a constructor for your class, C# creates one by default that instantiates the object and sets member variables to the default

 Constructor - live demo

 Reusing constructors

  • A constructor can invoke another constructor in the same object by using the this keyword
  • this can be used with or without parameters
  • any parameters in the constructor are available as parameters to this

 Reusing constructors

Methods and properties

 Methods

  • Methods are class members that execute some action (some code, some algorithm)
    • Could be static or per instance
    • Could have any access modifier
  • ​Instance methods are called through the object (instance)
class Person
{
    public void PrintName()
    {
        Console.WriteLine("Some name here");
    }
}
// Using it
Person person = new Person();
person.PrintName();

 Properties

  • Properties expose object's data to the 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 (examples)
    • Read and write
  • Simplify the writing of code

 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

 Properties

 Dynamic Properties

  • Properties are not obligatory bound to a class field – can be calculated dynamically
class Person
{
    private string firstName;
    private string lastName;

    public Person(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public string FullName
    {
        get
        {
            return this.firstName + this.lastName;
        }
    }
}

 Automatic Properties

  • Properties could be defined without an underlying field behind them
    • It is automatically created by the compiler
class Person
{
    public Person(string name)
    {
        this.FullName = name;
    }

    public string FullName { get; set; }
}

Enumerations

 Enumerations

  • Enumerations are types that hold a value from a fixed set of named constants
  • Declared by enum keyword in C#
    • By default the underlying type of each element in the enum is int.
    • When you do not specify values for the elements in the enumerator list, the values are automatically incremented by 1

 Enumerations

Keep object state valid

 Object State

  • Constructors and properties can keep the object's state correct
    • This is known as encapsulation in OOP
    • Can force validation when creating / modifying the object's 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

 Object State

Summary

 Summary

  • Classes define specific structure for objects
    • Objects are particular instances of a class
  • Classes define fields, methods, constructors, properties and other members
    • Access modifiers limit the access to class members
  • Constructors are invoked when creating new class instances and initialize the object's internal state
  • Enumerations define a fixed set of constants
  • Properties expose the class data in safe, controlled way
    • ​Validation must be done in the setter

 Throwing Exceptions

  • When raising an exception always pass to the constructor good explanation message
     
  • When throwing an exception always pass a good description of the problem
     
  • Exceptions can decrease the application performance
    • Throw exceptions only in situations which are really exceptional and should be handled
    • Do not throw exceptions in the normal program control flow (e.g. for invalid user input)

Questions?

[C# OOP] Classes - Part 1

By telerikacademy

[C# OOP] Classes - Part 1

  • 1,250