Presentation is loading. Please wait.

Presentation is loading. Please wait.

David Čamdžić Kompas Xnet Začnimo na začetku - C#.

Similar presentations


Presentation on theme: "David Čamdžić Kompas Xnet Začnimo na začetku - C#."— Presentation transcript:

1 David Čamdžić Kompas Xnet Začnimo na začetku - C#

2

3 C# appeared in 2002 with the release of.NET 1.0 C# was developed by Microsoft and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270:2006) C#‘s original author is Anders Hejlsberg (author of Turbo Pascal, Delphi and TypeScript) C# was designed to be an optimal Windows development language Briefly about C#

4 Simple, modern, general-purpose object-oriented programming language encompassing strong typing, imperative, declarative, functional, generic and component-oriented programming disciplines Very popular, used by millions of developers Easy to learn, yet very powerful Briefly about C#

5 C#.NET is in a sense one step removed from a typical high-level language C# runs using a „Virtual Machine” or „Common Language Runtime“ The physical computer simulates a virtual computer that runs your program The.NET Platform

6 Bad programs crash the virtual machine, not the real machine Easier to deploy software written for the virtual machine If a virtual machine exists for Macs or Linux or Windows, then the same program can run anywhere Why a virtual machine?

7 CLR and JIT compiling

8 Programming coverage in C# Methods, Classes, Arrays Iteration, Control Structures Variables, Expressions Data Types

9 Case-Sensitive: sumOfAverages, SumOfAverages, SUMOFAVERAGES PascalCasing for class names and method names camelCasing for method arguments and local variables Use noun or noun phrases to name a class Avoid using SCREAMINGCAPS for constants or read-only variables Naming conventions

10 C# has two different types of keywords, contextual keywords and reserved keywords. Contextual keywords are only treated as keywords in certain situations. Reserved keywords are treated like keywords in all situations. Both are always lowercase Keywords

11 Namespaces are used as a means of categorizing items in the.NET Framework Qualified names use period characters (.) between namespace levels Within a namespace, you can define nested namespaces, also using the namespace keyword. Namespaces

12 Variables

13 The first character of a variable name must be either a letter, an underscore character ( _ ), or the at symbol (@). Subsequent characters may be letters, underscore characters, or numbers. Variable naming

14 Value type instances are allocated on the stack Value type variables can be assigned a value directly Primitive Data Types: Int, Float, Char User Defined Structures (Structs) Can not derive from each other Can not have explicit constructors Data types: Value types

15 Built-in types C# type CTS (Common Type System) type intSystem.Int32 uintSystem.UInt32 sbyteSystem.SByte byteSystem.Byte shortSystem.Int16 ushortSystem.UInt16 longSystem.Int64 ulongSystem.UInt64 floatSystem.Single doubleSystem.Double decimalSystem.Decimal charSystem.Char stringSystem.String objectSystem.Object

16 Reference type instances are allocated in the heap Common types: strings, arrays, class types, delegates Contains the address of a location in memory where the data referred to by that variable is stored When the variable is not referencing any object the variable will be null. Will not be destroyed until C#’s garbage collection system determines that it is no longer needed. Data types: reference types

17 An array can be Single-Dimensional, Multidimensional or Jagged The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance. The default values of numeric array elements are set to zero, and reference elements are set to null. Arrays

18 A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null. Arrays are zero indexed: an array with n elements is indexed from 0 to n-1. Array elements can be of any type, including an array type. Arrays

19 Left to Right Primary: x.y, f(x), a[x], x++, x-- Unary: +, -, !, ~, ++x, --x, (T)x Shift: > Relational and type testing:, =, is, as Equality: ==, != Logical Expressions: &, ^, | Conditional Expressions &&, ||, ?: Expressions and Assignment Statements

20 Conditional expressions

21 While Do While For Loop For Each Loop Iterative statements

22 Methods and their signatures define how a class should behave Can not be nested Can be passed as parameters called Delegates Can have any return type including user defined and void Methods

23 Classes

24

25 Begining of class definition Inherited (base) class Fields Constructor Property

26 Classes Property Method End of class definition

27 Class Definition and Members

28 Access Modifiers

29 Constructors

30 Fields contain data for the class instance Can be arbitrary type Have given scope Can be declared with a specific value Fields class Student { private string name; private int course = 1; private string speciality; protected Course[] coursesTaken; private string remarks = "(no remarks)"; }

31 Constants public class MathConstants { public const string PI_SYMBOL = "π"; public const double PI = 3.1415926535897932385; public const double E = 2.7182818284590452354; public const double LN10 = 2.30258509299405; public const double LN2 = 0.693147180559945; }

32 Read-Only Fields public class ReadOnlyDemo { private readonly int size; public ReadOnlyDemo(int size) { this.size = size; // can not be further modified! }

33 Properties

34 Defining properties

35 Properties are not obligatory bound to a class field – can be calculated dynamically: Dynamic Properties public class Rectangle { private float width; private float height; public float Area { get { return width * height; }

36 Automatic Properties 36 class UserProfile { public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } UserProfile profile = new UserProfile { FirstName = "Bill", LastName = "Gates", UserId = 91112 };

37 Static Members 37

38 Static vs. Non-Static 38

39 Structures 39

40 When to use Structures? 40

41 When to use Structures? 41

42 What are Delegates?

43

44 Delegates – Example // Declaration of a delegate public delegate void SimpleDelegate(string param); public class TestDelegate { public static void TestFunction(string param) { Console.WriteLine("I was called by a delegate."); Console.WriteLine("I got parameter {0}.", param); } public static void Main() { // Instantiation of а delegate SimpleDelegate simpleDelegate = new SimpleDelegate(TestFunction); // Invocation of the method, pointed by a delegate simpleDelegate("test");} }

45 Anonymous Methods

46 Using Delegates: Standard Way class SomeClass { delegate void SomeDelegate(string str); public void InvokeMethod() { SomeDelegate dlg = new SomeDelegate(SomeMethod); dlg("Hello"); } void SomeMethod(string str) { Console.WriteLine(str); }

47 The same thing can be accomplished by using an anonymous method: Using Anonymous Methods class SomeClass { delegate void SomeDelegate(string str); public void InvokeMethod() { SomeDelegate dlg = delegate(string str) { Console.WriteLine(str); }; dlg("Hello"); }

48 Events

49 Events in.NET public event EventHandler Click;

50 Events in.NET Button button = new Button("OK"); button.Click += delegate { Console.WriteLine("Button clicked."); };

51 Events are not the same as member fields of type delegate The event is processed by a delegate Events can be members of an interface unlike delegates Calling of an event can only be done in the class it is defined in By default the access to the events is synchronized (thread-safe) Events vs. Delegates

52 System.EventHandler Delegate public delegate void EventHandler(object sender, EventArgs e);

53 EventHandler – Example public class Button { public event EventHandler Click; public event EventHandler GotFocus; public event EventHandler TextChanged; } public class ButtonTest { private static void Button_Click(object sender, EventArgs eventArgs) { Console.WriteLine("Call Button_Click() event"); } public static void Main() { Button button = new Button(); button.Click += Button_Click; }

54 Interfaces

55 Interfaces – Example public interface IPerson { string Name // property Name { get; set; } DateTime DateOfBirth // property DateOfBirth { get; set; } int Age // property Age (read-only) { get; } }

56 Interfaces – Example interface IShape { void SetPosition(int x, int y); int CalculateSurface(); } interface IMovable { void Move(int deltaX, int deltaY); } interface IResizable { void Resize(int weight); void Resize(int weightX, int weightY); void ResizeByX(int weightX); void ResizeByY(int weightY); }

57 Classes and structures can implement (support) one or many interfaces Interface realization must implement all its methods If some methods do not have implementation the class or structure have to be declared as an abstract Interface Implementation

58 Interface Implementation – Example class Rectangle : IShape, IMovable { private int x, y, width, height; public void SetPosition(int x, int y) // IShape { this.x = x; this.y = y; } public int CalculateSurface() // IShape { return this.width * this.height; } public void Move(int deltaX, int deltaY) // IMovable { this.x += deltaX; this.y += deltaY; }

59 Abstract method is a method without implementation Left empty to be implemented by descendant classes When a class contains at least one abstract method, it is called abstract class Mix between class and interface Inheritors are obligated to implement their abstract methods Can not be directly instantiated Abstract Classes

60 Abstract Class – Example abstract class MovableShape : IShape, IMovable { private int x, y; public void Move(int deltaX, int deltaY) { this.x += deltaX; this.y += deltaY; } public void SetPosition(int x, int y) { this.x = x; this.y = y; } public abstract int CalculateSurface(); }

61 Inheritance is the ability of a class to implicitly gain all members from another class The class whose methods are inherited is called base (parent) class The class that gains new functionality is called derived (child) class Inheritance establishes an is-a relationship between classes: A is B Inheritance

62 All class members are inherited Fields, methods, properties, … In C# classes can be inherited The structures in C# can not be inherited Inheritance allows creation of deep inheritance hierarchies In.NET there is no multiple inheritance, except when implementing interfaces Inheritance

63 We must specify the name of the base class after the name of the derived class In the constructor of the derived class we use the keyword base to invoke the constructor of the base class How to Define Inheritance? public class Shape {...} public class Circle : Shape {...} public Circle (int x, int y) : base(x) {...}

64 Inheritance – Example public class Mammal { private int age; public Mammal(int age) { this.age = age; } public int Age { get { return age; } set { age = value; } } public void Sleep() { Console.WriteLine("Shhh! I'm sleeping!"); }

65 Inheritance – Example public class Dog : Mammal { private string breed; public Dog(int age, string breed): base(age) { this.breed = breed; } public string Breed { get { return breed; } set { breed = value; } } public void WagTail() { Console.WriteLine("Tail wagging..."); }

66 Inheritance – Example static void Main() { // Create 5 years old mammal Mamal mamal = new Mamal(5); Console.WriteLine(mamal.Age); mamal.Sleep(); // Create a bulldog, 3 years old Dog dog = new Dog("Bulldog", 3); dog.Sleep(); dog.Age = 4; Console.WriteLine("Age: {0}", dog.Age); Console.WriteLine("Breed: {0}", dog.Breed); dog.WagTail(); }

67

68


Download ppt "David Čamdžić Kompas Xnet Začnimo na začetku - C#."

Similar presentations


Ads by Google