4. Defining Members

About this Tutorial

Objectives

Delegates will learn to develop applications using C# 4.5. After completing this course, delegates will be able to:

  • Use Visual Studio 2012 effectively
  • Create commercial C# Web Applications
  • Develop multi-threaded applications, Use WCF and LINQ

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of C# will also find the content beneficial.

Prerequisites

No previous experience in C# programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Download Solutions

HTML tutorial


Overview
Members are things that are declared inside a class. Members help in representing the class‘s data and behaviour when the application is running. The members that could be inside a class include – fields, constants, properties, constructors, destructors, events, operators etc…

Class members can be specified individually with any one of the following accessibility:

  • Public – accessible by any code within current or external assembly
  • Protected – accessibility within the same class or its derived class
  • Private – accessibility within the same class
  • internal – accessibility within current assembly
  • protected internal – accessibility within current assembly or classes derived from containing class

Estimated Time – 1 Hour

Not what you are looking? Try the next tutorial – Going Further with Types and Members

Lab 1: A closer look at parameters

Lab 1: A closer look at parameters
  1. Parameter Passing Modes- Parameters can be out or ref to output values for example:
    int num1=10, num2=20;
    //
    MethodIn(num1, num2);
     Console.WriteLine("After MethodIn, num1={0}, num2={1}", num1, num2);
    //
    MethodRef(ref num1, ref num2);
     Console.WriteLine("After MethodRef, num1={0}, num2={1}", num1, num2);
    //
    int prod, quot;
    MethodOut(num1, num2, out prod, out quot);
     Console.WriteLine("After MethodOut, prod={0}, quot={1}", prod, quot);
    //
    public void MethodIn(int x, int y)
    { int temp = x; x = y; y = temp; }
    ...
  2. View code file.
  3. You can declare a variable-length parameter list and this is done by Defining the final parameter as an array, and prefix it with the params keyword:
    private static void DisplayThings(string message, params object[] things)
    {
     Console.WriteLine(message);
     foreach (object obj in things)
      Console.WriteLine(" {0}", obj);
    }

    This allows the client to pass a comma-separated list of parameters or an array:
    DisplayThings("Fav things:",
        "Jayne", "Emily", "Tom", 3, ConsoleColor.Red);
    DisplayThings("Least fav things:",
        new object[] {"Cardiff City", ConsoleColor.Blue});
  4. View code file.
  5. Optional Parameters- You can define default values for parameters therefore making the parameter optional. This is done by using the equal sign to set a default value:
    public class Car
    {
     private string model;
     ...
     public void Accelerate(int delta, bool changeGear = false)
     {
      if (changeGear)
       currentGear++;
      currentSpeed += delta;
     }
     ...
    }
    // AND CALLING THE METHOD
     aCar.Accelerate(20); // Equivalent to: aCar.Accelerate(20, false);
     aCar.Accelerate(20, true); // Pass in explicit parameter this time.
  6. View code file.
  7. Named Parameters – Traditionally in C#, method parameters are resolved positionally e.g.
    aCar.Accelerate(20, true);
  8. You can now pass named parameters – Use the syntax paramName: paramValue; these are useful if there are lots of optional parameters and you only want to pass some of them e.g.
    aCar.Accelerate(delta: 20);
    aCar.Accelerate(delta: 20, changeGear: true);
    aCar.Accelerate(changeGear: true, delta: 20);
  9. View code file.

Lab 2: Construction and destruction

Lab 2: Construction and destruction
  1. Constructors Recap – You can define constructors to initialize objects; A constructor is called when you create an object. A parameter-less constructor is provided for free in every class/struct but you can define any number of constructors –
    public MyClass(int param1, double param2, ...)
    {...}
  2. Initializer Lists – You can use initializer lists in a constructor, to do this add a colon after the constructor header. You can use an ‘initializer list’ to forward to other constructors in the current type this will be done depending on what parameters have been input –
    : this(param1, param2, ...)
  3. Defining Destructors – You can define a destructor in a class symbolised by “~” at the start of the destructor. The destructor is called when an object is garbage collected known as object finalization as clean-up code is placed in the destructor –
    ~MyClass() {...}
Lab
  1. Open up Visual Studio 2013, New Project>C#>Windows>Console Application – What we are going to be making is an investment system that will allow a user to add money to an investment account on years.
  2.  
    App

  3. Call this application DemoMembers and at the start make sure to add the using statement
    using System;
  4. First we are going to set up our data that we are going to hold such as the customers name, an integer to hold the number of years and a double array to hold all investments made. –
    private string customer;
    private int numYears;
    private double[] investments;
  5. Next to add is our constructor classes – These work by having a base constructor, if the parameters given match that of either the top two constructors those will be run first before moving onto the bottom constructor (base):
    public class Investment
    {
     private string customer;
     private int numYears;
     private double[] investments;
     public Investment(string customer, int numYears, double initialSum)
      : this(customer, numYears) // Calls ctor 3.
     {
      Invest(initialSum, 0);
     }
     public Investment(string customer, int numYears, params double[] initialSums)
      : this(customer, numYears) // Calls ctor 3.
     {
      foreach (double inv in initialSums)
       Invest(inv, 0);
     }
     public Investment(string customer, int numYears)
     {
     this.customer = customer;
     this.numYears = numYears;
     this.investments = new double[numYears];
     }
  6. And now we are going to add our destructor class to finalize anything that was made in the constructors, this is normally things such as closing files, ending connections that were made etc…
     ~Investment()
     {
      Console.WriteLine("Inside ~Investment() destructor for {0}.", customer);
      Console.WriteLine("Closing investment for {0}", this);
     } ...
  7. Now to create the business logic to run behind the scenes; One method will add a value to a given year. The other method will get the value from the sum of all the years investments and one >method to return a string with all the data inside –
    public void Invest(double amount, int year)
     {
      if (year < numYears)
      {
      investments[year] += amount;
      }
     }
     public double CurrentValue
     {
      get
      {
      ...
     }
  8. Now running the client code to use our new methods for our banking investments:
    Console.WriteLine("Creating objects.");
     Investment inv1 = new Investment("Hayley", 6, 10000.0);
     Investment inv2 = new Investment("Claire", 9, 2000, 4000, 1000);
    Console.WriteLine("Using objects.");
     inv1.Invest(100, 1);
     inv1.Invest(200, 2);
     inv1.Invest(300, 3);
    Console.WriteLine("Investment 1: {0}", inv1.ToString());
     inv2.Invest(1000, 1);
     inv2.Invest(2000, 2);
     inv2.Invest(3000, 3);
    Console.WriteLine("Investment 2: {0}", inv2.ToString());
  9. View code file.
  10. Program

Lab 3: Properties

Lab 3: Properties
  1. Properties blur the distinction between fields and methods:
    • To the client, properties look like fields.
    • To client they store data associated with the type.
    • To the class writer, properties are implemented by blocks of code.
    • Properties can have a ‘getter’ and/or a ‘setter’ – they map to methods in underlying IL code.
    • There are two kinds – Scalar properties and Indexed properties.
  2. For a scalar property – you get or set a single value by specifying the name and type of the property. Properties are as easy to use as public data, but more encapsulated e.g. make it read-only or write only and maybe perform some validation in the setter –
    public class Product
    {
     // Declare a variable to hold the description.
     private string mDescription;
     // Property to get and set the description.
     public string Description
     {
      get
      {
       return mDescription;
      }
      set
      {
       mDescription = value;
      }
     }
    }
    // CLIENT CODE
    Product aProduct = new Product(); // Create a Product object
    aProduct.Description = "Chef Anton's Gumbo Mix"; // Set Description property.
    Console.WriteLine("{0}", aProduct.Description); // Set Description property.
  3. View code file.
  4. IlDASM

  5. Read-Only and Write-Only Properties:
    • For read-only property; only provide a “getter”.
    • For a write-only property; only provide a “setter”.
  6. Auto-Implemented Properties:
    • .NET supports of auto-implemented propertiesShort-cut syntax for properties that just get/set a value. The compiler automatically generates an appropriate backing field and implementation for the get set bodies –
      public class Person
      {
       public string Name { get; set; }
       public DateTime Dob { get; set; }
       public string Nationality { get; set; }
       ...
       public Person(string name, DateTime dob, string nationality)
       {
        Name = name;
        Dob = dob;
        Nationality = nationality;
       }
       ...
    • View code file.
    • If you want to implement read-only auto-implemented properties: you need to make the setter private e.g.
      public class Person
      {
       public DateTime Dob { get; private set; }
       ...
      }
    • View code file.

 

Well done. You have completed the tutorial in the C# course. The next tutorial is

5. Going Further with Types and Members


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top