static members and namespaces static members, indexers, operators, namespaces softuni team technical...
TRANSCRIPT
Static Members and Namespaces
Stati c Members, Indexers,Operators, Namespaces
SoftUni TeamTechnical TrainersSoftware Universityhttp://softuni.bg
2
1. Static Members
2. Indexers
3. Operators
4. Namespaces
Table of Contents
+-=/
[5]
Static MembersStatic vs. Instance Members
4
Static members are associated with a class (type) Rather than with an object (instance) Defined with the modifier static
Static can be used for Constructors Fields Properties Methods Events
Static Members
5
Static: Associated with a type (class), not with an instance Initialized just before the type is used for the first time Cleared from memory on program exit
Non-Static: The opposite, associated with an instance (object) Initialized when the constructor is called Cleared from memory by the garbage collector
Static vs. Non-Static
6
Static Counter – Examplepublic class Person{ private static int instanceCounter = 0; public static int PersonCounter { get { return Person.instanceCounter; } }
public string Name { get; set; }
public Person(string name = null) { Person.instanceCounter++; this.Name = name; }}
7
Static Members – Examplestatic class SqrtPrecalculated{ public const int MaxValue = 10000; // Static field private static int[] sqrtValues;
// Static constructor static SqrtPrecalculated() { sqrtValues = new int[MaxValue + 1]; for (int i = 0; i < sqrtValues.Length; i++) { sqrtValues[i] = (int)Math.Sqrt(i); } } (example continues)
8
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 MembersLive Demo
Indexers
public int this [int index]{ …}
var value = list[5];
11
Indexers provide indexed access to class data Predefine the [] operator for a certain type
Like when accessing array elements
Can accept one or multiple parameters
Defining an indexer:
Indexers
IndexedType t = new IndexedType(50);int i = t[5];t[0] = 42;
personInfo["Svetlin Nakov", 28]
public int this [int index] { … }
12
Indexers – Examplestruct BitArray32{ private uint value;
// Indexer declaration public int this [int index] { get { if (index >= 0 && index <= 31) { // Check the bit at position index if ((this.value & (1 << index)) == 0) return 0; else
return 1; }
(the example continues)
13
Indexers – Example (2) else { throw new IndexOutOfRangeException( String.Format("Index {0} is invalid!", index)); }}
set{ if (index < 0 || index > 31) throw new IndexOutOfRangeException( String.Format("Index {0} is invalid!", index)); if (value < 0 || value > 1) throw new ArgumentException( String.Format("Value {0} is invalid!", value)); // Clear the bit at position index this.value &= ~((uint)(1 << index)); // Set the bit at position index to value this.value |= (uint)(value << index);}
IndexersLive Demo
Operators Overloading
16
In C# operators can be overloaded (redefined) by developers The priority of operators cannot be changed Not all operators can be overloaded
Overloading an operator in C# Looks like a static method with 2 parameters:
Overloading Operators
public static Matrix operator *(Matrix m1, Matrix m2){ return new m1.Multiply(m2);}
17
Overloading is allowed on: Unary operators
Binary operators
Operators for type conversion Implicit type conversion Explicit type conversion (type)
Overloading Operators (2)
!, ~, ++, --, true and false
+, -, *, /, %, &, |, ^, <<, >>, ==, !=, >, <, >= and <=
18
Overloading Operators – Example
public static Fraction operator -(Fraction f1,Fraction f2){ long num = f1.numerator * f2.denominator - f2.numerator * f1.denominator; long denom = f1.denominator * f2.denominator;
return new Fraction(num, denom);}
public static Fraction operator *(Fraction f1,Fraction f2){ long num = f1.numerator * f2.numerator; long denom = f1.denominator * f2.denominator;
return new Fraction(num, denom);}
(the example continues)
19
Overloading Operators – Example (2)
// Unary minus operatorpublic static Fraction operator -(Fraction fraction){ long num = -fraction.numerator; long denom = fraction.denominator; return new Fraction(num, denom);}
// Operator ++ (the same for prefix and postfix form)public static Fraction operator ++(Fraction fraction){ long num = fraction.numerator + fraction.denominator; long denom = Frac.denominator; return new Fraction(num, denom);}
Overloading OperatorsLive Demo
NamespacesGrouping Classes
22
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
C# namespaces in are similar to C++ namespaces and Java packages Allow defining types with duplicated names
E.g. a class named Button is found in Windows Forms, in WPF and in ASP.NET Web Forms
Namespaces
23
Including a namespace The using directive is put at the start of the file
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 including a namespace with using its nested namespaces
are not included
Including Namespaces
using System.Windows.Forms;
24
Types placed in namespaces can be used without using directive, by their full name:
using can create aliases for namespaces :
Including Namespaces (2)
using IO = System.IO;using WinForms = System.Windows.Forms;
IO.StreamReader reader = IO.File.OpenText("file.txt");
WinForms.Form form = new WinForms.Form();
System.IO.StreamReader reader = System.IO.File.OpenText("file.txt");
25
Divide the types in your applications into namespaces When the types are too many (more than 15-20) Group the types logically in namespaces according to their
purpose
Use nested namespaces when the types are too many E.g. for a Tetris game you may have the following namespaces: Tetris.Core, Tetris.Data, Tetris.Web, Tetris.HTML5Client
Defining Namespaces
26
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
Defining Namespaces (2)
27
Namespaces – ExampleNamespaces – Examplenamespace SoftUni.Data{ public struct Faculty { // … } public class Student { // … } public class Professor { // … } public enum Specialty { // … }}
28
Namespaces – Example (2)Namespaces – Example (2)namespace SoftUni.UI{ public class StudentAdminForm : System.Windows.Forms.Form { // … } public class ProfessorAdminForm : System.Windows.Forms.Form { // … }}namespace SoftUni{ public class AdministrationSystem { public static void Main() { // … } }}
29
Recommended directory structure and class organization Recommended directory structure and class organization
Namespaces – Example (3)
NamespacesLive Demo
31
Static members are shared between all instances Instance members are per object
Indexers allow indexed access to class data Operator overloading redefines the
functionality of the standard operators Namespaces logically group code
around some particular functionality
Summary
Questions??
??
?
?
??
?
?
OOP – Static Members and Namespaces
https://softuni.bg/courses/oop/
License
This course (slides, examples, demos, videos, homework, etc.)is licensed under the "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International" license
33
Attribution: this work may contain portions from "OOP" course by Telerik Academy under CC-BY-NC-SA license
Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education,
Profession and Job for Software Developers softuni.bg
Software University @ Facebook facebook.com/SoftwareUniversity
Software University @ YouTube youtube.com/SoftwareUniversity
Software University Forums – forum.softuni.bg