Static Members, Structures, Enumerations, Generic Classes, Namespaces Learning & Development Team Telerik Software Academy.

Slides:



Advertisements
Similar presentations
Generics Programming in C# Generics CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Advertisements

Classes, Constructors, Properties, Events, Static Members, Interfaces, Inheritance, Polymorphism Svetlin Nakov Telerik Corporation
Object Oriented Programming with Java
OOP Abstraction Classes Class Members: Properties & Methods Instance (object) Encapsulation Interfaces Inheritance Composition Polymorphism Using Inheritance.
CLASS INHERITANCE Class inheritance is about inheriting/deriving properties from another class. When inheriting a class you are inheriting the attributes.
Execute Blocks of Code Multiple Times Telerik Software Academy C# Fundamentals – Part 1.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Objects contains data and methods Class – type of object Create class first Then object or instance String – defined class String s; // creates instance.
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
What is a class? a class definition is a blueprint to build objects its like you use the blueprint for a house to build many houses in the same way you.
Lecture 9 Concepts of Programming Languages
1.11 Introduction to OOP academy.zariba.com 1. Lecture Content 1.What is OOP and why use it? 2.Classes and objects 3.Static classes 4.Properties, fields.
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Corporation
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Inheritance using Java
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Other Types in OOP Enumerations, Structures, Generic Classes, Attributes Svetlin Nakov Technical Trainer Software University
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Java Programming: Program Design Including Data Structures 1 Vectors The class Vector can be used to implement a list Unlike an array, the size of a Vector.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Classes and Multiform Projects.
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
Using the Standard.NET Framework Classes Svetlin Nakov Telerik Software Academy academy.telerik.com.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
[ISRAR ALI] Hammad Khan. The namespace keyword is used to declare a scope. Making software components reusable can result in naming collisions (two classes.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
OOP Basic Topics Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Other Types in OOP Enumerations, Structures, Generic Classes, Attributes SoftUni Team Technical Trainers Software University
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
CSCI 3328 Object Oriented Programming in C# Chapter 9: Classes and Objects: A Deeper Look – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Static Members, Structures, Enumerations, Generic Classes, Namespaces Telerik Software Academy Object-Oriented Programming.
Generics SoftUni Team Technical Trainers Software University
Static Members and Namespaces
C# for C++ Programmers 1.
Creating and Using Objects, Exceptions, Strings
Object-Oriented Programming with C#
University of Central Florida COP 3330 Object Oriented Programming
Defining Classes – Part II
Structs.
OOP’S Concepts in C#.Net
Lecture 9 Concepts of Programming Languages
Pass by Reference, const, readonly, struct
Using Classes and Objects
An Introduction to Java – Part II
CSCI 3328 Object Oriented Programming in C# Chapter 9: Classes and Objects: A Deeper Look – Exercises UTPA – Fall 2012 This set of slides is revised from.
Interfaces.
The University of Texas – Pan American
CIS 199 Final Review.
Class.
Lecture 9 Concepts of Programming Languages
Presentation transcript:

Static Members, Structures, Enumerations, Generic Classes, Namespaces Learning & Development Team Telerik Software Academy

1. Static Members 2. Structures in C# 3. Generics 4. Namespaces 5. Indexers 6. Operators 7. Attributes 2

Static vs. Instance 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 4

 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 5

static 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) 6

// Static method // Static method public static int GetSqrt(int value) public static int GetSqrt(int value) { return sqrtValues[value]; return sqrtValues[value]; }} class SqrtTest { static void Main() static void Main() { Console.WriteLine( Console.WriteLine( SqrtPrecalculated.GetSqrt(254)); SqrtPrecalculated.GetSqrt(254)); // Result: 15 // Result: 15 }} 7

Live Demo

 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, …  Always have a parameterless constructor  It cannot be removed  Mostly used to store data (bunch of fields) 10

struct Point { public int X { get; set; } public int X { get; set; } public int Y { get; set; } public int Y { get; set; }} struct 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; }} enum Edges { Straight, Rounded } (example continues) (example continues) 11

struct 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 Edges Edges { get; set; } public Edges Edges { get; set; } public Square(Point location, int size, public Square(Point location, int size, Color surfaceColor, Color borderColor, Color surfaceColor, Color borderColor, Edges edges) : this() Edges edges) : 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; this.Edges = edges; this.Edges = edges; }} 12

Live Demo

Parameterizing Classes

 Generics allow defining parameterized classes that process data of unknown (generic) type  The class can be instantiated (specialized) with different particular types  Example: List  List / List / List  Example: List  List / List / List  Generics are also known as "parameterized types" or "template types"  Similar to the templates in C++  Similar to the generics in Java 15

public class GenericList public class GenericList { public void Add(T element) { … } public void Add(T element) { … }} class GenericListExample { static void Main() static void Main() { // Declare a list of type int // Declare a list of type int GenericList intList = GenericList intList = new GenericList (); new GenericList (); // Declare a list of type string // Declare a list of type string GenericList stringList = GenericList stringList = new GenericList (); new GenericList (); }} 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 during the instantiation 16

Live Demo

 Generic class declaration:  Example: 18 class MyClass : class-base where where { // Class body // Class body} class MyClass : BaseClass where T : new() { // Class body // Class body}

 Parameter constraints clause:  Example: public class MyClass public class MyClass where T: class, IEnumerable, new() {…} public SomeGenericClass public SomeGenericClass where type-parameter : primary-constraint, secondary-constraints, constructor-constraint

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

Live Demo

public static T Min (T first, T second) where T : IComparable where T : IComparable { if (first.CompareTo(second) <= 0) if (first.CompareTo(second) <= 0) return first; return first; else else return second; return second;} static void Main() { int i = 5; int i = 5; int j = 7; int j = 7; int min = Min (i, j); int min = Min (i, j);}

Live Demo

 Namespaces logically group type definitions  May contain classes, structures, interfaces, enumerators and other types and namespaces  Can not 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 25

 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 begging of the file  When includes a namespace with using its subset of namespaces is not included using System.Windows.Forms; 26

 Types, placed in namespaces, can be used and without using directive, by their full name:  using can create allies for namespaces : using IO = System.IO; using WinForms = System.Windows.Forms; IO.StreamReader reader = IO.File.OpenText("file.txt"); IO.File.OpenText("file.txt"); WinForms.Form form = new WinForms.Form(); System.IO.StreamReader reader = System.IO.File.OpenText("file.txt"); System.IO.File.OpenText("file.txt"); 27

 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 28

 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 29

namespace SofiaUniversity.Data { public struct Faculty public struct Faculty { // … // … } public class Student public class Student { // … // … } public class Professor public class Professor { // … // … } public enum Specialty public enum Specialty { // … // … }}

namespace SofiaUniversity.UI { public class StudentAdminForm : System.Windows.Forms.Form public class StudentAdminForm : System.Windows.Forms.Form { // … // … } public class ProfessorAdminForm : System.Windows.Forms.Form public class ProfessorAdminForm : System.Windows.Forms.Form { // … // … }} namespace SofiaUniversity { public class AdministrationSystem public class AdministrationSystem { public static void Main() public static void Main() { // … // … } }}

 Recommended directory structure and classes organization in them 32

Live Demo

Indexers

Indexers  Indexers provide indexed access class data  Predefine the [] operator for certain type  Like when accessing array elements  Can accept one or multiple parameters  Defining an indexer: 35 IndexedType t = new IndexedType(50); int i = t[5]; t[0] = 42; personInfo["Svetlin Nakov", 28] public int this [int index] { … }

Indexers – ExampleIndexers – Example 36 struct BitArray32 { private uint value; private uint value; // Indexer declaration // Indexer declaration public int this [int index] public int this [int index] { get get { if (index >= 0 && index = 0 && index <= 31) { // Check the bit at position index // Check the bit at position index if ((value & (1 << index)) == 0) if ((value & (1 << index)) == 0) return 0; return 0; else else return 1; return 1; } (the example continues) (the example continues)

Indexers – Example (2)Indexers – Example (2) 37 else else { throw new IndexOutOfRangeException( throw new IndexOutOfRangeException( String.Format("Index {0} is invalid!", index)); String.Format("Index {0} is invalid!", index)); }}set{ if (index 31) if (index 31) throw new IndexOutOfRangeException( throw new IndexOutOfRangeException( String.Format("Index {0} is invalid!", index)); String.Format("Index {0} is invalid!", index)); if (value 1) if (value 1) throw new ArgumentException( throw new ArgumentException( String.Format("Value {0} is invalid!", value)); String.Format("Value {0} is invalid!", value)); // Clear the bit at position index // Clear the bit at position index value &= ~((uint)(1 << index)); value &= ~((uint)(1 << index)); // Set the bit at position index to value // Set the bit at position index to value value |= (uint)(value << index); value |= (uint)(value << index);}

Indexers Live DemoLive Demo

Operators OverloadingOperators Overloading

Overloading OperatorsOverloading 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: 40 public static Matrix operator *(Matrix m1, Matrix m2) { return new m1.Multiply(m2); return new m1.Multiply(m2);}

Overloading Operators (2)Overloading Operators (2)  Overloading is allowed on:  Unary operators  Binary operators  Operators for type conversion  Implicit type conversion  Explicit type conversion (type) 41 +, -, !, ~, ++, --, true and false +, -, *, /, %, &, |, ^, >, ==, !=, >, = and >, ==, !=, >, = and <=

Overloading Operators – Example 42 public static Fraction operator -(Fraction f1,Fraction f2) { long num = f1.numerator * f2.denominator - long num = f1.numerator * f2.denominator - f2.numerator * f1.denominator; f2.numerator * f1.denominator; long denom = f1.denominator * f2.denominator; long denom = f1.denominator * f2.denominator; return new Fraction(num, denom); return new Fraction(num, denom);} public static Fraction operator *(Fraction f1,Fraction f2) { long num = f1.numerator * f2.numerator; long num = f1.numerator * f2.numerator; long denom = f1.denominator * f2.denominator; long denom = f1.denominator * f2.denominator; return new Fraction(num, denom); return new Fraction(num, denom);} (the example continues)

Overloading Operators – Example (2) 43 // Unary minus operator public static Fraction operator -(Fraction fraction) { long num = -fraction.numerator; long num = -fraction.numerator; long denom = fraction.denominator; long denom = fraction.denominator; return new Fraction(num, denom); 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 num = fraction.numerator + fraction.denominator; long denom = Frac.denominator; long denom = Frac.denominator; return new Fraction(num, denom); return new Fraction(num, denom);}

Overloading OperatorsOverloading Operators Live DemoLive Demo

Attributes Applying Attributes to Code ElementsApplying Attributes to Code Elements

What are Attributes?What are Attributes? .NET attributes are:  Declarative tags for attaching descriptive information in the declarations in the code  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 46

Applying Attributes – ExampleApplying Attributes – Example  Attribute's name is surrounded by square brackets []  Placed before their target declaration  [Flags] attribute indicates that the enum type can be treated like a set of bit flags 47 [Flags] // System.FlagsAttribute public enum FileAccess { Read = 1, Read = 1, Write = 2, Write = 2, ReadWrite = Read | Write ReadWrite = Read | Write}

Attributes with Parameters (2)Attributes with Parameters (2)  Attributes can accept parameters for their constructors and public properties  The [DllImport] attribute refers to:  System.Runtime.InteropServices. DllImportAttribute  " user32.dll " is passed to the constructor  " MessageBox " value is assigned to EntryPoint 48 [DllImport("user32.dll", EntryPoint="MessageBox")] public static extern int ShowMessageBox(int hWnd, string text, string caption, int type); string text, string caption, int type);… ShowMessageBox(0, "Some text", "Some caption", 0);

Set a Target to an AttributeSet a Target to an Attribute  Attributes can specify its target declaration:  See the Properties/AssemblyInfo.cs file 49 // target "assembly" [assembly: AssemblyTitle("Attributes Demo")] [assembly: AssemblyCompany("DemoSoft")] [assembly: AssemblyProduct("Entreprise Demo Suite")] [assembly: AssemblyVersion(" ")] [Serializable] // [type: Serializable] class TestClass { [NonSerialized] // [field: NonSerialized] [NonSerialized] // [field: NonSerialized] private int status; private int status;}

Live Demo

Custom AttributesCustom 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 51

Custom Attributes – ExampleCustom Attributes – Example 52 [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Interface, AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true)] AllowMultiple = true)] public class AuthorAttribute : System.Attribute { public string Name { get; private set; } public string Name { get; private set; } public AuthorAttribute(string name) public AuthorAttribute(string name) { this.Name = name; this.Name = name; }} // Example continues // Example continues

Custom Attributes – Example (2) 53 [Author("Svetlin Nakov")] [Author("Nikolay Kostov")] class CustomAttributesDemo { static void Main(string[] args) static void Main(string[] args) { Type type = typeof(CustomAttributesDemo); Type type = typeof(CustomAttributesDemo); object[] allAttributes = object[] allAttributes = type.GetCustomAttributes(false); type.GetCustomAttributes(false); foreach (AuthorAttribute attr in allAttributes) foreach (AuthorAttribute attr in allAttributes) { Console.WriteLine( Console.WriteLine( "This class is written by {0}. ", attr.Name); "This class is written by {0}. ", attr.Name); } }}

Defining, Applying and Retrieving Custom Attributes Live Demo

 Classes define specific structure for objects  Objects are particular instances of a class  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 "value-type" classes  Generics are parameterized classes 55

Questions?

57 1. Create a structure Point3D to hold a 3D-coordinate {X, Y, Z} in the Euclidian 3D space. Implement the ToString() to enable printing a 3D point. 2. Add a private static read-only field to hold the start of the coordinate system – the point O{0, 0, 0}. Add a static property to return the point O. 3. Write a static class with a static method to calculate the distance between two points in the 3D space. 4. Create a class Path to hold a sequence of points in the 3D space. Create a static class PathStorage with static methods to save and load paths from a text file. Use a file format of your choice.

58 5. Write a generic class GenericList 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. 6. Implement auto-grow functionality: when the internal array is full, create a new array of double size and move all elements to it.

59 7. Create generic methods Min () and Max () for finding the minimal and maximal element in the GenericList. You may need to add a generic constraints for the type T. 8. Define a class Matrix to hold a matrix of numbers (e.g. integers, floats, decimals). 9. Implement an indexer this[row, col] to access the inner matrix cells. 10. Implement the operators + and - (addition and subtraction of matrices of the same size) and * for matrix multiplication. Throw an exception when the operation cannot be performed. Implement the true operator (check for non-zero elements).

11. Create a [Version] attribute that can be applied to structures, classes, interfaces, enumerations and methods and holds a version in the format major.minor (e.g ). Apply the version attribute to a sample class and display its version at runtime. 60

 C# Telerik Academy  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com