Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# - OOP TTU IT College 2017-2018, Autumn SEMESTER http://enos.itcollege.ee/~akaver/CSHARP Andres käver.

Similar presentations


Presentation on theme: "C# - OOP TTU IT College 2017-2018, Autumn SEMESTER http://enos.itcollege.ee/~akaver/CSHARP Andres käver."— Presentation transcript:

1 C# - OOP TTU IT College , Autumn SEMESTER Andres käver

2 C# - OOP Object Oriented Programming – OOP Clean Code Defensive Coding
Iterative, Agile API Design Patterns Domain Driven Design MS UWA, ASP.NET, etc

3 C# - class Object vs Class Class is the usable instance of Object
class ExampleClass { public int SomeInt { get; set; } public int GetSomeIntPlusOne() return SomeInt + 1; } Object vs Class Not the same thing!!! Class is the code Class is the usable instance of Object Creating a class is often called “instantiation” Class is the blueprint, object is the house made according to blueprint static void Main(string[] args) { ExampleClass exampleClass = new ExampleClass(); }

4 C# - class members Fields Properties class SampleClass {
public string SampleStringField; public string SampleStringProperty { get; set; } } Fields Like variables, can be read and set directly Properties Have get and set procedures, more control over values Auto-implemented property: public string SampleStringProperty { get; set; } Write in VS: prop+TAB for editor help Need more control – have backing field and provide logic for storing and retrieving class SampleClass { private int _sample; public int Sample get { return _sample; } set { _sample = value; } }

5 C# - class members Methods Action, that the object can perform
Can have several implementations of the same method, called overloads. Number of parameters or types has to differ. class SampleClass { public int SampleMethod(string sampleParam) return 0; } public int SampleMethod(int sampleParam) return 1;

6 C# - class members Constructors
Class method, executed automatically when object is created. Can run only once, before any other code in class. Overloads Default constructor is parameterless, auto created by compiler. Name of the constructor method is identical to class name VS shortcut: ctor+TAB class SampleClass { public SampleClass() }

7 C# - class members Destructors
GC (Garbage Collection) takes care of object destruction and memory management in most cases. Needed in case of unmanaged resources. There can only be one destructor in class. Almost never used – IDisposable is recommended pattern. class SampleClass { ~SampleClass() //destructor }

8 C# - Events Enable a class or object to notify other classes or objects when something of interest occurs. Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces. Advanced topic….

9 C# - Nested classes A class defined within another class is called nested. By default, the nested class is private. class Container { class Nested } Container.Nested nestedInstance = new Container.Nested();

10 C# - Access Modifiers and Levels
All classes and class members can specify what access level they provide to other classes by using access modifiers. public private protected internal protected internal Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibility of its containing type.

11 C# - Access Modifiers and Levels
public The type or member can be accessed by any other code in the same assembly or another assembly that references it. private The type or member can only be accessed by code in the same class. protected The type or member can only be accessed by code in the same class or in a derived class. internal The type or member can be accessed by any code in the same assembly, but not from another assembly. protected internal The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

12 C# - assembly and namespace
An assembly provides a fundamental unit of physical code grouping. It is an Output Unit. It is a unit of Deployment and an unit of versioning. Assemblies contain MSIL (MS Intermediate Language) code. Namespace A namespace provides a fundamental unit of logical code grouping. It is a collection of names wherein each name is unique. They form the logical boundary for a group of classes. Namespace must be specified in project properties.

13 C# - Static classes and members
A static member of the class is a property, procedure, or field that is shared by all instances of a class. Static classes have static members only and cannot be instantiated. Static members also cannot access non-static properties, fields or methods static class SampleStaticClass { public static string SampleString = "Sample String"; } Console.WriteLine(SampleStaticClass.SampleString);

14 C# - Anonymous types Create objects without writing a class definition for the data type. Compiler generates a class for you. The class has no usable name and contains the properties you specify in declaring the object. var sampleObject = new { FirstProperty = "A", SecondProperty = "B" };

15 C# - Inheritance Inheritance enables you to create a new class that reuses, extends, and modifies the behavior that is defined in another class. The class whose members are inherited is called the base class. The class that inherits those members is called the derived class. All classes in C# implicitly inherit from the Object class that supports .NET class hierarchy and provides low-level services to all classes.

16 C# - Inheritance To inherit from base class
class BaseClass { } class DerivedClass : BaseClass To inherit from base class To specify, that class cannot be used as base class To specify, that class can only be used as base class and cannot be instantiated public sealed class A { } public abstract class B { }

17 C# - Overriding Members
By default, a derived class inherits all members from its base class. If you want to change the behavior of the inherited member, you need to override it. You can define a new implementation of the method, property or event in the derived class. The following modifiers are used to control how properties and methods are overridden: virtual, override, abstract, new

18 C# - Overriding members
virtual Allows a class member to be overridden in a derived class. override Overrides a virtual (overridable) member defined in the base class. abstract Requires that a class member to be overridden in the derived class. new Hides a member inherited from a base class

19 C# - Overriding members - virtual
The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. Cannot be used with: static, abstract, private, override class BaseClassRoot { public virtual double Area(double side) return side*side; }

20 C# - Overriding members - override
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event. class DerivedClassCube : BaseClassRoot { public override double Area(double side) return base.Area(side)*6; }

21 C# - Overriding members - abstract
The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.

22 C# - Overriding members - abstract
abstract class BaseClass { public abstract double Area(double side); } class BaseClassRoot : BaseClass public override double Area(double side) return side*side; class DerivedClassCube : BaseClassRoot return base.Area(side)*6; Abstract class cannot be instantiated Sealed not possible Abstract method is also virtual Abstract methods only in abstract class No implementation of methods No static or virtual

23 C# - C# - Overriding members - new
When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version. Although you can hide members without using the new modifier, you get a compiler warning. If you use new to explicitly hide a member, it suppresses this warning. Override extends, new hides class BaseClass { public double Area(double side) return 0; } class BaseClassRoot : BaseClass public new double Area(double side) return side * side;

24 C# - Interfaces Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. An interface represents a contract, in that a class that implements an interface must implement every aspect of that interface exactly as it is defined. Most of modern oop programming is based on interfaces!

25 C# - Interfaces Interfaces members are public
You have to implement every method in interface Abstract class can use interfaces Convention – all interfaces start with capital letter I You can implement more than one interface interface ISampleInterface { void DoSomething(); } class SampleClassWithInterface : ISampleInterface public void DoSomething() throw new NotImplementedException();

26 C# - Generics Classes, structures, interfaces and methods in the .NET Framework can include type parameters that define types of objects that they can store or use. The most common example of generics is a collection, where you can specify the type of objects to be stored in a collection. public class SampleGeneric<T> { public T Field; } SampleGeneric<string> sampleObject = new SampleGeneric<string>(); sampleObject.Field = "Sample string";

27 C# - Delegates A delegate is a type that defines a method signature, and can provide a reference to any method with a compatible signature. You can invoke (or call) the method through the delegate. Delegates are used to pass methods as arguments to other methods.

28 C# - Delegates public delegate void SampleDelegate(string str);
class SampleClassDelegate { // Method that matches the SampleDelegate signature. public static void SampleMethod(string message) // Add code here. } // Method that instantiates the delegate. void SampleDelegate() SampleDelegate sd = SampleMethod; sd("Sample string");

29 C# - Methods A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method. The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started.

30 C# - Methods Method signature
Methods are declared in a class or struct by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method. A return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to.

31 C# - Methods – reference vs value
Value types bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort When value type is passed to method, copy is passed Changes to the argument wont change original value Use ref keyword for passing value types by reference When reference type argument is passed, you will change the original (objects)

32 C# - Methods - ref Ref has to be used in declaration
Ref has to be used in calling public void RefExample(ref int x) { x = x*x; } var x = 5; RefExample(ref x);

33 C# - Methods - out class OutExample { static void Method(out int i) i = 44; } static void Main() int value; Method(out value); // value is now 44 The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.

34 C# - Constructors No parameters – default constructor. If class has no constructors defined, compiler autogenerates one for you – unless class is static. Constructors can be overloaded Default constructor is not required public class Employee { public int Salary; public Employee(int annualSalary) Salary = annualSalary; } public Employee(int weeklySalary, int numberOfWeeks) Salary = weeklySalary * numberOfWeeks;

35 C# - Constructors A constructor can use the base keyword to call the constructor of a base class. The base keyword can be used with or without parameters. Any parameters to the constructor can be used as parameters to base In a derived class, if a base-class constructor is not called explicitly by using the base keyword, the default constructor, if there is one, is called implicitly. public class Manager : Employee { public Manager(int annualSalary) : base(annualSalary) //Add further instructions here. }

36 C# - Constructors A constructor can invoke another constructor in the same object by using the this keyword. Like base, this can be used with or without parameters, and any parameters in the constructor are available as parameters to this. public class Employee { public int Salary; public Employee(int annualSalary) Salary = annualSalary; } public Employee(int weeklySalary, int numberOfWeeks) : this(weeklySalary * numberOfWeeks)

37 C# - Constructors Constructors can be marked as
public private protected internal protected internal A constructor can be declared static by using the static keyword. Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members. No access modifiers or parameters are allowed.

38 C# - this The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method. To qualify members hidden by similar names To pass an object as a parameter to other methods To declare indexers Static member functions, because they exist at the class level and not as part of an object, do not have a this pointer

39 C# - this qualify members hidden by similar names Indexer
public class Employee { private int salary; public Employee(int salary) this.salary = salary; } public int this[int param] { get { return array[param]; } set { array[param] = value; } }

40 C# - Extension methods Extension methods enable you to "add" methods to existing types without creating a new derived type. public static class MyExtensions { public static int WordCount(this String str) return str.Split(new[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; } string s = "Hello Extension Methods"; int i = s.WordCount();

41 C# - Named arguments Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. A named argument can follow positional arguments. A positional argument cannot follow a named argument.

42 C# - Named arguments class NamedExample {
static void Main(string[] args) // The method can be called in the normal way, by using positional arguments. Console.WriteLine(CalculateBMI(123, 64)); // Named arguments can be supplied for the parameters in either order. Console.WriteLine(CalculateBMI(weight: 123, height: 64)); Console.WriteLine(CalculateBMI(height: 64, weight: 123)); // Named arguments can follow positional arguments. Console.WriteLine(CalculateBMI(123, height: 64)); } static int CalculateBMI(int weight, int height) return (weight * 703) / (height * height);

43 C# - Optional arguments
The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. Optional parameters are defined at the end of the parameter list, after any required parameters. public void ExampleMethod(int required, string optionalStr = "default string", int optionalInt = 10)

44 THE END

45 C# -

46 C# -

47 C# - NOTES/TODO!!!! Methods Extension Methods Structs Events
Extension Methods Structs Events


Download ppt "C# - OOP TTU IT College 2017-2018, Autumn SEMESTER http://enos.itcollege.ee/~akaver/CSHARP Andres käver."

Similar presentations


Ads by Google