Classes - Part 2
Telerik Academy Alpha

 

 Table of contents

Static 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 Instance

  • Static:
    • Associated with a type (class), not with an instance
  • Instance:
    • associated with an instance (object)
  • Static:
    • Initialized just before the type is used for the first time
  • Instance:
    • Initialized when the constructor is called

 Static example

 Static vs Instance

  • Static class cannot be instantiated.
    • You cannot use the new keyword to create an object of that type
    • Container for set of methods
      • System.Math
  • ​​Contains only:
    • Static members
    • Cannot be instantiated
    • Is sealed
    • Cannot contain Instance constructors

 Static class vs Instance class

  • Static class is basically the same as instance class
    • with only static members
    • and a private constructor
  • The advantage of a static class is that the compiler checks if there are instance members
  • Static members are not subject of the garbage collector

Structures

 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, …

 Structures

  • Always have a parameterless constructor
    • It cannot be removed
  • Typically used to encapsulate small groups of related variables
    • coordinates of a rectangle
    • characteristics of an item in an inventory
  • ​Cannot inherit from another structures
    • ​but can implement an interface

 Structures - live demo

Generics

 Generics

  • Generics allow defining parameterized classes that process data of unknown (generic) type
    • The class can be instantiated with 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

 Generics - live demo

 Generics

  • T is an unknown type, parameter of the class
  • T can be used in any method in the class
  • T can be replaced with int/string/long/etc. during the instantiation

 Generics

  • T is an unknown type, parameter of the class
  • T can be used in any method in the class
  • T can be replaced with int/string/long/etc. during the instantiation
class MyClass <type-parameter-list> : class-base
where <type-parameter-constraints-clauses>
{
  // Class body
}

// Example
class MyClass<T> : BaseClass
where T : new()
{
  // Class body
}

 Generic constraints

  • parameter constraint clause 
public SomeGenericClass<some parameters>
where type-parameter : primary-constraint,
	secondary-constraints,
	constructor-constraint

// Example
public class MyClass<T>
where T: class, IEnumerable<T>, new()
{…}

 Generic constraints

  • Primary constraint:
    • class (reference type parameters)
    • struct (value type parameters)
  • Secondary constraints:
    • Interface derivation
    • Base class derivation
  • Constructor constraint:
    • new() – parameterless constructor constraint

    More info

 Generic methods

  • A generic method is a method that is declared with type parameters

 

public static T Min<T>(T first, T second)
    where T : IComparable<T>
{
    if (first.CompareTo(second) <= 0)
    {
       return first;
    }
    else
    {    
       return second;
    }
}

Namespaces

 Namespaces

  • Namespaces logically group type definitions
  • May contain classes, structures, interfaces, enumerators and other types and namespaces
  • Cannot contain methods and data directly
  • Can be allocated in one or several files
  • Namespaces in .NET are similar to namespaces in C++ and packages in Java
  • Allows definition of types with duplicated names
    • E.g. a type named Button is found in Windows Forms, in WPF and in ASP.NET Web Forms

 Namespaces

  • Including a namespace
    • The using directive is put at the start of the file
      • using System.Windows.Forms;
    • using allows direct use of all types in the namespace
    • Including is applied to the current file
    • The directive is written at the beginning of the file
    • When includes a namespace with using its subset of namespaces is not included

 Namespaces

  • Types, placed in namespaces, can be used and without using directive, by their full name
System.IO.StreamReader reader = System.IO.File.OpenText("file.txt");
  • using can create alias for namespaces
using IO = System.IO;
using WinForms = System.Windows.Forms;

IO.StreamReader reader = IO.File.OpenText("file.txt");
WinForms.Form form = new WinForms.Form();

 Namespaces

  • Divide the types in your applications into namespaces
    • When the types are too much (more than 15-20)
    • Group the types logically in namespaces according to their purpose
  • Use nested namespaces when the types are too much
    • E.g. for Tetris game you may have the following namespaces: Tetris.Core, Tetris.Web, Tetris.Win8, Tetris.HTML5Client

 Namespaces

  • Distribute all public types in files identical with their names
    • E.g. the class Student should be in the file Student.cs
  • Arrange the files in directories, corresponding to their namespaces
    • The directory structure from your project course-code have to reflect the structure of the defined namespaces

 Using inside vs outside namespace

  • Microsoft convention is to put the using outside namespaces
  • Analysis tools (StyleCop, ReSharper) encourage you to move them inside namespace
    • It is a personal taste or team convention
    • However there is a difference between the two approaches

 Using inside vs outside namespace

Indexers

 Indexers

  • Indexers enable objects to be indexed in a similar manner to arrays.

    • A get accessor returns a value.

    • A set accessor assigns a value.

  • The this keyword is used to define the indexer.

  • The value keyword is used to define the value being assigned by the set indexer.

 Indexers

  • Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.

  • Indexers can be overloaded.

  • Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.

 Indexers

  • Indexers provide indexed access class data
  • Predefine the [] operator for certain type
    • Like when accessing array elements
IndexedType t = new IndexedType(50);
int i = t[5];
t[0] = 42;
  • Can accept one or multiple parameters
personInfo["John Doe", 25]

 Indexers - live demo

Overloading operators

 Overloading operators

  • In C# some operators can be overloaded(redefined) by developers
    • The priority of operators can not be changed
    • Not all operators can be overloaded
  • Overloading an operator in C#
    • Looks like a static method with 2 operands
public static Matrix operator *(Matrix m1, Matrix m2)
{
    return new m1.Multiply(m2);
}

 Overloading operators

Operators Overloadability
+, -, !, ~, ++, --, true, false These unary operators can be overloaded.
+, -, *, /, %, &, |, ^, <<, >> These binary operators can be overloaded.
==, !=, <, >, <=, >= The comparison operators can be overloaded (but see the note that follows this table).
&&, || The conditional logical operators cannot be overloaded, but they are evaluated using & and |, which can be overloaded.
[] The array indexing operator cannot be overloaded, but you can define indexers.
(T)x ​The cast operator cannot be overloaded, but you can define new conversion operators (see explicit and implicit).
+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.
​=, ., ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is, new, sizeof, typeof These operators cannot be overloaded.

NOTES: The comparison operators, if overloaded, must be overloaded in pairs; that is, if == is overloaded, != must also be overloaded. The reverse is also true, and similar for < and >, and for <= and >=.

 Overloading operators

Attributes

 What are Attributes?

  • .NET attributes are:
    • ​Metadata
    • Data about your objects/methods/properties.
      • Saved in the assembly at compile time
        • Objects derived from System.Attribute
          • Can be accessed at runtime (through reflection) and manipulated by many tools
  • Developers can define custom attributes

 Attributes

  • Attribute`s name is surrounded by square brackets []
    • Placed before their target declaration

 Custom attributes

  • NET developers can define their own custom attributes
    • Must inherit from System.Attribute class
    • Their names must end with 'Attribute'
    • Possible targets must be defined via [AttributeUsage]
    • Can define constructors with parameters
    • Can define public fields and properties

 Custom attributes - live demo

Questions?

[C# OOP] Classes - Part 2

By telerikacademy

[C# OOP] Classes - Part 2

  • 1,331