3. Defining Types

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
C# sharp is a strongly typed language – This means that every expression that will form a value, any variable, any constant will have a type associated with it. There are more complex types than that of integer and double but also types for file systems, collections etc…

The general information stored about a type –

  • Storage Space
  • Members it contains e.g. fields and methods
  • Max and min values
  • Base type it inherits from

Estimated Time – 2 Hours

Not what you are looking? Try the next tutorial – Defining Members

Lab 1: Essential concepts

Lab 1: Essential concepts
  1. What is the difference between a Reference Type and a Value Type.
    • Reference types represent the ‘major entities’ in your OO design, such as classes and interfaces. They are Allocated on the ‘managed heap‘ and will exist until the garbage collector periodically de-allocates unreachable objects.
    • Value types represent the ‘small things’ in your app, such as numerical types. They are allocated on the stack and will be de-allocated at the end of a method assuming it is a local variable.
    • RefandVal

  2. Type Visibility – It can be defined in two manners:
    • public = accessible from any assembly –
      public class ThisClassCanBeAccessedFromAnyAssembly {...}
    • internal = accessible from this assembly (default) –
      internal class ThisClassIsInternalToThisAssembly {...}
    • View Code file.
  3. Member Visibility:
    • Public – Unrestricted accessibility.
    • Private – Accessible only by this type (default).
    • Protected – Accessible by this type and subtypes.
    • Internal – Accessible by types in this assembly.
    • Protected internal – Accessible by this type and subtypes, and by types in this assembly.
    • public class MyClass
      {
       public int mPublicMember = 0;
       private int mPrivateMember = 0;
        int mAnotherPrivateMember = 0;
       protected int mProtectedMember = 0;
       internal int mInternalMember = 0;
       protected internal int mProtectedInternalMember = 0;
      }

  4. View Code file.

Lab 2: Classes, objects, and arrays

Lab 2: Classes, objects, and arrays
  1. Defining classes – here is a simple class, a class effectively represent your blue prints for creating an object and when you use that blueprint you end up with a product. For example this is a blueprint for a bank account and so you have variables for balance, the holders name and methods like deposit and withdraw.
    public class Account
    {
     private string holder;
     private double balance;
     public void Deposit(double amount)
     {
      this.balance += amount;
     }
     public void Withdraw(double amount)
     {
      this.balance -= amount;
     }
     public override string ToString()
     {
      return this.holder + ", £" + this.balance;
     }
     ...
    }

  2. View Code file.
  3. Constructors:
    • You can define constructors to initialize objects; a constructor is called when you create an object. You can define any number of constructors assuming they have different parameters.
      public class Account
      {
       private string holder;
       private double balance;
       public Account(string holder, double balance)
       {
        this.holder = holder;
        this.balance = balance;
       }
       ...
      }
    • View Code file.
  4. Creating an Object – Template, this can also be called insatiate, e.g you can insatiate an object. The main part to pay attention to is that you use the keyword new to do this and supply the needed variables at the same time-
    Typename variable = new Typename(params-to-constructor);
  5. Creating an Object – Example
    static class ClassesAndObjectsDemo
    {
     public static void DoDemo()
     {
     Account acc1 = new Account("Emily", 2000); // creates an account for Emily, with starting balance of 2000
     acc1.Deposit(500);
     acc1.Withdraw(200);
     System.Console.WriteLine("{0}", acc1);
     }
    }

  6. View Code file.
  7. Implicitly-Typed Local Variables:
    • .NET allows you to declare implicitly-typed local variables.
    • Use the var type in a local variable declaration.
    • Initialize the variable with a suitable (non-null) value.
    • The compiler “knows” the variable type.
    • var myName = "Andy"; // myName is a String.
      var myAge = 21; // myAge is an int.

  8. Creating Arrays:
    • An array is a contiguous collection of items of the same type.
    • Accessed using [] via zero-based index.
    • Use new to create array – For an array of value types, array elements are housed in-situ.
    • int[] a1 = new int[10]; // creates array of size 10 (0-9) for integers
      int[] a2 = {200, 201, 202, 203};
      string[] a3 = new string[10];
      string[] a4 = {"And", "There", "He", "Goes"};

    • View Code file.
    • Creating multi-dimensional arrays and jagged arrays –
      int[,] rect = new int[5,5]; // Multi-dimension array
      int[][] jagged = new int[5][]; // Jagged array
      for (int i = 0; i < rect.GetLength(0); i++)
      {
       for (int j = 0; j < rect.GetLength(1); j++)
       {
        Console.WriteLine("rect["+i+","+j+"] is " + rect[i,j]);
       }
      }
      for (int i = 0; i < jagged.Length; i++)
      {
       Console.Write("Size of jagged["+i+"]? ");
      ....
      }
    • View Code file.

  9. Namespaces:
    • A namespace is a logical cluster of related types – You can define namespaces corresponding to the UML packages in your OO design.
    • .NET namespaces don’t imply a particular deployment layout
      namespace Accounting
      {
       public class BankAccount {...} // Superclass
       public class SavingsAccount : BankAccount {...} // Subclass
       public class CurrentAccount : BankAccount {...} // Subclass
       public class OverdraftFacility {...} // Misc. class
      }
    • View Code file.
    • Use a using statement to import types from a namespace –
      using System; // Import types from System namespace.
      using Accounting; // Import types from Accounting namespace.
      namespace DemoTypes
      {
       static class UseNamespaceDemo
       {
        public static void DoDemo()
        {
         BankAccount[] accs = new BankAccount[]
         {
          new SavingsAccount(),
         ...
      }
    • View Code file.
    Lab
  1. We are going to create a Bank account Class using windows forms allowing you to simulate creating accounts for customers.
  2. Open Visual Studio, New Project>C#>Windows>Windows Forms Application and name this “BankAccount”
     
    FormCreation
  3. Add in the display items as shown in the picture and name them as so –
     
    UI
  4. Names of Controls:
    • txtName, txtAmount, txtWithdraw, txtDeposit, txtDisplay.
    • BtnAdd, BtnWithdraw, BtnDeposit.
  5. Now just to add the code so our lovely UI works.
  6. Add this code to the Form1 class variables so we can use it throughout the application –
    Account acc1;
  7. lets add the Account class First – Open up Form1.cs and add this code once the partial Form1 class ends
    public class Account
    {
     private string holder;
     private double balance;
     public void Deposit(double amount)
     {
      this.balance += amount;
     }
     public void Withdraw(double amount)
     {
      this.balance -= amount;
     }
    ... // See code file
    }
  8. Now double click each button in the Form1 designer and it will open up the Form1.cs and create an event handler for you.
    • Add Account
      private void BtnAdd_Click(object sender, EventArgs e)
       {
        double Money =0;
        String Name = "";
        Money = Convert.ToDouble(txtAmount.Text);
        Name = txtName.Text;
        acc1 = new Account(Name, Money);
        txtDisplay.Text = acc1.ToString();
       }
    • Deposit Account
      private void BtnDeposit_Click(object sender, EventArgs e)
       {
        acc1.Deposit(Convert.ToDouble(txtDeposit.Text));
        txtDisplay.Text = acc1.ToString();
       }
    • Withdraw Account
      private void BtnWithdraw_Click(object sender, EventArgs e)
       {
        acc1.Withdraw(Convert.ToDouble(txtWithdraw.Text));
        txtDisplay.Text = acc1.ToString();
       }
    • View Code file.
  9. Now you can run the application
     
    WorkingApp

Lab 3: Value types

Lab 3: Value types
  1. Structures:
    • Structures represent ‘incidental types’ in a design – Money, temperature, date and time, etc…
    • Identity is not significant – Objects passed/assigned by value, not by reference.
    • Allocation and deallocation – Allocated using new and de-allocated at end of enclosing block.
    • Structures inherit implicitly from System.Value – Can’t have parameter-less constructors.
    • Example Structure –
      public struct Money : IComparable
      {
       private int mCentsAmount;
       private const string mCurrencySymbol = "$";
       public Money(int dollars, int cents)
       {
        mCentsAmount = (dollars * 100) + cents;
       }
       public Money(double amount)
       {
        mCentsAmount = (int)(amount * 100);
       }
       public override string ToString()
       {
      ...
      }
    • View Code file.
    • Using structures –
      static class StructuresDemo
      {
       public static void DoDemo()
       {
        Money[] values = new Money[5]; // Create an array
        values[0] = new Money(9, 50); // Copy new objects into array slots
        values[1] = new Money(4, 80);
        values[2] = new Money(8, 70);
        values[3] = new Money(2.50);
        values[4] = new Money(6);
        Console.WriteLine("Unsorted array:");
        foreach (Money v in values) // Use foreach to iterate over array
        {
        ....
      }
    • View Code file.
    • Simple Types – The C# simple types are actually structures e.g. int is equivalent to system.int32 –
      byte b = 0;
       sbyte sb = 0;
      short i16 = 0; ushort u16 = 0;
       int i32 = 0; uint u32 = 0;
      long i64 = 0; ulong u64 = 0;
       float f = 0.0f;
      double d = 0.0;
       decimal dec = 0.0m;
      char c = 'A';
       bool bl = false;
      Console.WriteLine("byte: {0,-15} [{1,32}:{2,32}]",
           b.GetType().ToString(),
           byte.MinValue, byte.MaxValue);
      ...etc...
    • View Code file.
  2. Enumerations – Enums define a bounded set of whole numbers –
    public enum Connection
    {
     DialUp, ISDN, BroadBand, None=-1
    }
    Connection con = Connection.ISDN;
    Console.WriteLine("Connection: {0}", con);
    Console.WriteLine("Integral value: {0}", (int)con);
    • Underlying type is int, or you can specify:
      public enum MonthName : byte
      {
       January=1, February, March, April, May, June, July, August, ...
      }
      MonthName mn = MonthName.July;
      Console.WriteLine("Month name: {0}", mn);
      Console.WriteLine("Integral value: {0}", (byte)mn);
    • View Code file.

Lab 4: Nullable types

Lab 4: Nullable types
  1. Introducing Nullable Types:
    • A nullable type is any value type (primitive, struct, or enum), that can contain a null value.
    • To declare a nullable variable, append ? to value-type name –
      int? myNullableInt; // Nullable primitive
      Point? myNullablePoint; // Nullable struct
      DayOfWeek? myNullableDow; // Nullable enum
    • View Code file.
    • You can assign null to any nullable-type variable –
      myNullableInt = null; // Converts null to int?
      myNullablePoint = null; // Converts null to Point?
      myNullableDow = null; // Converts null to DayOfWeek?

    • View Code file.
    • .NET allows implicit conversion from T to T? –
      myNullableInt = 10; // int to int?
      myNullablePoint = new Point(10, 20); // Point to Point?
      myNullableDow = DayOfWeek.Friday; // DayOfWeek to DayOfWeek?
  2. Using Nullable types:
    • Nullable types provide the following properties: HasValue property and Value property –
      Point? myNullablePoint;
      ...
      if (myNullablePoint.HasValue) // also OK: if (myNullablePoint != null)
      {
       Point p = myNullablePoint.Value;
       Console.WriteLine("X coordinate: " + p.X);
       Console.WriteLine("Y coordinate: " + p.Y);
      }
      else
      {
       Console.WriteLine("No value at the moment");
      }
    • View Code file.

 

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

4. Defining 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