Classes and methods

TABLE OF CONTENTS

  • Classes and Objects
  • Declaring an object
    • Class members
  • Using Methods
    • What is a Method?
    • Why to Use Methods?
    • Declaring and Creating
    • Calling Methods
  • Methods with Parameters
    • Passing Parameters
    • Returning Values

Classes and Objects

Classes and Objects

  • Classes and Structs are essentially templates from which you can create Objects.
  • Structs differ from classes in the way that they were stored in memory and accessed.
    • They are different in some other features also such as structs doesn’t support inheritance while classes supports.
    • Structs looks very similar to classes the main difference is use the keyword struct instead of class to declare them.

Classes and Objects (2)

  • For both classes and structs you use the keyword new to declare an instance.
  • The data and functions within the class are known as class members. They are also termed as data members and function members.

Student obj = new Student(); //For Classes to create objects
StudentsStruct obj1 = new StudentsStruct(); //For structs
					

What are Objects?

  • Software objects model real -world objects or abstract concepts
    • Examples: bank, account, customer, dog, bicycle, queue
  • Real - world objects have states and behaviors
    • Account' states: holder, balance, type
    • Account' behaviors: withdraw, deposit, suspend

What are Objects? (2)

  • How do software objects implement real -world objects?
    • Use variables/data to implement states
    • Use methods/functions to implement behaviors
  • An object is a software bundle of variables and related methods

Objects Represent

  • Things from the real world
    • checks
    • people
    • shopping list
  • Things from the computer world
    • numbers
    • characters
    • queues
    • arrays

What is a Class?

  • The formal definition of class (by Google):
    • Classes act as templates from which an instance of an object is created at run time. Classes define the properties of the object and the methods used to control the object's behavior.

Classes

  • Classes provide the structure for objects
    • Define their prototype, act as template
  • Classes define:
    • Set of attributes.
      - Represented by variables and properties.
      - Hold their state
    • Set of actions (behavior)
      - Represented by methods

Classes (2)

  • A class defines the methods and types of data associated with an object

Objects

  • An object is a concrete instance of a particular class
  • Creating an object from a class is called instantiation
  • Objects have state
    • Set of values associated to their attributes
  • Example:
    • Class: Account
    • Objects: my account, your account

Class Members

    Data Members
  • These are the members that contains the data for the class. They are fields, constants and events
  • Data members can be either static or instance
  • Fields are any variable associated with the class. Once you have instantiated class object you can access the filed member using Obj.FieldName syntax

Class Members (2)

  • Constants also associated with class same way as fields. You can declare constants with const keyword.
  • Events are class members that allow an object to notify a caller when something noteworthy happens.

Student obj = new Student();
obj.firstName = “Alex”;
					

Class Members (3)

    Function Members:
  • These members provides the functionality for manipulating the data in the class. They includes methods, properties, constructors, finalizers, operators and indexers.
  • Methods can be either static or instance methods.
  • Properties are set of functions that can be associated from the client in the similar way to the public fields of the class.

Class Members (4)

    Properties
  • The idea of property is that it is a method of pair of methods that are dressed to look like a field as far as any client code is concerned.
  • A good example is Hight property of Windows Forms.
  • Compared to fields with the help of properties you can validate input values and make any necessary code execution.
  • Eg: myForm.Height = 400; //Sets hight of window and resizes window.

Class Members (5)

  • To define properties you can use get and set accessories.
  • If you define only get then it will become read only property. Similarly if you define only set then it will become write only property.
  • C# does allows the set and get accessors to have different access modifiers. Take note one of the accessors must follow the access level of the property.

Class Members (6)

  • Constructors are special functions those are called automatically when an object is created.
  • Operators are used to make some actions on user defined types.
  • Indexers allow your object to be indexed in the same way as array or collections.

Class Members (7)

    Constructors
  • You can declare a method that has the same name as the containing class and that doesn’t have any return type.
  • For your class if you not supply any constructor then compiler will provide default constructor.
  • It is a basic constructor it will initialize all the fields by zeroing them out (null reference for reference types, zero for numeric data types and false for bool types).

Class Members (8)

  • You can also overload the constructors. They follow the same rules as method overloading.
  • It is also possible to specify access specifiers on constructors also.
  • It is also possible to write static no-parameter constructors for a class. Such a constructors will be executed only once.
  • This static constructor is used to initialized static fields or properties.
  • There is no guarantee that when static constructor will be executed. Executes at most once.

Class Members (9)

    Methods in C#
  • In C# every function must be associated with a class or struct.
  • Passing parameters to methods either by reference or by value.
  • In C# all the parameters are passed by value unless you explicitly says as reference types.
  • By default simple primitive types are passed by value whereas arrays are passed by reference.

Class Members (10)

  • Any variable passing by value is the default. However with the help of ref keyword you can force the variable to be passed as reference.
  • You will also need to add ref keyword when you invoke method.
  • If function need to output more then one value, use out keyword.

[modifiers] return_type MethodName([parameters])
{
	//Method Body
}
						

Class Members (11)

  • C# supports method overloading. You simple declare methods with the same name but different numbers or types of parameters.

public static void Main()
{
	ShowString();
	ShowString("Category");
}
static void ShowString()
{
	Console.WriteLine("Popular"); // Use default argument
}
static void ShowString(string value)
{
	Console.WriteLine("Popular" + value);
}
									

Class Members (12)

  • The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.

// Override the CalculatePay method to take bonus into account
public override decimal CalculatePay()
{
    return basepay + salesbonus;
}
						

Class Members (13)

    C# readonly fields
  • You want a variable whose value shouldn’t be changed but the value is not known until runtime. To address this type of scenarios C# supports readonly fields.
    • The readonly field gives bit more flexible then constants.
    • For readonly fields you can make initial value based on calculations. But constants it is not supported.

Class Members (14)

  • You can assign a value to readonly field inside constructors only.
  • It is also possible for readonly filed to be instance rather then static field, having a different value for each instance of a class.
  • If a class contains nothing but static methods and properties the class it self become static.

Using Methods

Methods

  • A method is a kind of building block that solves a small problem
    • A piece of code that has a name and can be called from the other code
    • Can take parameters and returna value
  • Methods allow programmers to construct large programs from simple pieces of logic
  • Methods are also known as functions, procedures and subroutines

Why use Methods?

  • More manageable programming
    • Split large problems into small pieces
    • Better organization of the program
    • Improve code readability
    • Improve code understandability
  • Avoiding repeating code
    • Improve code maintanability
  • Code reuse
    • Using existing methods several times

Declaring and reusing Methods

    Each method has a name
  • It is used to call the method
  • Describes the method's purpose

public static void FillMatrix(int[,] matrix)
{
    for (int i = 0; i < matrix.GetLength(0); i++)
    {
        for (int j = 0; j < matrix.GetLength(1); j++)
        {
            matrix[i, j] = -1;
        }
    }
}
						

Declaring and reusing Methods (2)

  • Methods declared static can be called by any other method (static or not)
    • This will be discussed later in details
  • The keyword void means that the method doen not return any result
  • Each method has a body
    • It contains the programming code
    • Surrounded by { and }

Declaring and reusing Methods (3)

  • Methods are always declared insside a class
  • main() is also a method like all others

class TestClass
{
    static void Main(string[] args)
    {
        // Display the number of command line arguments:
        System.Console.WriteLine(args.Length);
    }
}
						

Instance Methods

  • Methods manipulate the data of the object to which they belong or perform other tasks
  • Instance methods manipulate the data of a specified object or perform any other task. If a value is returned, it depends on the particular class instance
  • Syntax: The name of the instance, followed by the name of the method, separated by dot

Static Methods

  • Are commonfor all instances of a class (shared) between all instaces. Returned value depends only on the passed parameters.
  • No particular class instance is available
  • Syntax: The name of the class, followed by the name of the method, separated by dot

Methods with Parameters

Methods Parameters

  • To pass information to a method, you can use parameters (also known as arguments)
    • You can pass zero or several input values
    • You can pass values of different types
    • Each parameter has name and type
    • Parameters are assigned to particular values when the method is called
  • Parameters can change the methods behavior depending on the passed values

Methods Parameters (2)

  • Method's behavior depends on its parameters
  • Parameters can be of any type
    • int, double, string, etc.
    • Array, Object etc.
  • Methods can have as many parameters as needed

static int CalculateBMI(int weight, int height = 3)
{
    return (weight * 703) / (height * height);
}
						

Calling Methods with Parameters

  • To call a Methodand pass values to its parameters
    • Use method name, folloed by a list of expressions for each parameter.
  • Expressions must be of the same type as method's parameters (or compatible)
  • If the method requres a float expression, you can pass int instead
  • You can use the same order like in method delaration
  • For methods with no parameters do not forget the parantheses

Calling Methods with Parameters (2)


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));

        // Positional arguments cannot follow named arguments.
        // The following statement causes a compiler error.
        Console.WriteLine(CalculateBMI(weight: 123, 64));

        // Named arguments can follow positional arguments.
        Console.WriteLine(CalculateBMI(123, height: 64));
    }
}
						

Returning values from methods

  • A mthod can return a value to its caller
  • Returned value:
    • Can be assigned to a variable
    • can be used in expressions
    • Can be passed to another method

Returning values from methods (2)


class ReturnTest
{
    static double CalculateArea(int r)
    {
        double area = r * r * Math.PI;
        return area;
    }
    static void Main()
    {
        int radius = 5;
        double result = CalculateArea(radius);
        Console.WriteLine("The area is {0:0.00}", result);
        // Keep the console open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
// Output: The area is 78.54
					

Returning values from methods (3)

  • Defining methods that return a value
  • Instead of void, specify the type of data to return
  • The combination of method's name and parameters is called method signature
  • Use return keyword to return a result
office@e-dojo.it

EXERCISE

Problem 1: Say Hello

Write a method that asks the user for his name and prints Hello, <name>!

Problem 2: Get largest number

Write a method GetMax() with two parameters that returns the larger of two integers. Write a program that reads 3 integers from the console and prints the largest of them using the method GetMax().

EXERCISE (2)

Problem 3: English digit

Write a method that returns the last digit of given integer as an English word.

Problem 4: Appearance count

Write a method that counts how many times given number appears in a given array. Write a test program to check if the method is working correctly.

EXERCISE (3)

Problem 5: Larger than neighbours

Write program that reads an array of numbers and prints how many of them are larger than their neighbours. Write a method that checks if the element at given position in given array of integers is larger than its two neighbours (when such exist).

Problem 6: Reverse number

Write a method that reverses the digits of a given decimal number.
Examples - Input: 256; 123.45; Output 652; 54.321;

EXERCISE (4)

Problem 7: Solve tasks

  • Write a program that can solve these tasks:
    • Reverses the digits of a number
    • Calculates the average of a sequence of integers
    • Solves a linear equation a* x + b = 0
  • Create appropriate methods.
    • Provide a simple text-based menu for the user to choose which task to solve.
    • Validate the input data:
      • The decimal number should be non-negative
      • The sequence should not be empty

EXERCISE (5)

Problem 8: Triangle surface by side and altitude

Write program that calculates the surface of a triangle by given a side and an altitude to it.

  • Input
    • On the first line you will receive the length of a side of the triangle
    • On the second line you will receive the altitude to that side
  • Output
    • Print the surface of the rectangle with two digits of precision

EXERCISE (6)

Problem 8: Examples

Input Output
23.2 5
53.00

EXERCISE (7)

Problem 9: Triangle surface by side and altitude

You are given a sequence of positive integer values written into a string, separated by spaces. Write a function that reads these values from given string and calculates their sum. Write a program that reads a string of positive integers separated by spaces and prints their sum.

EXERCISE (8)

Problem 9: Examples

Input Output
43 68 9 23 318 461