C# Tutorial : Lesson 7 - Creating Value Types & Reference Types - Part II

free web hosting
Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > .NET (VB, C# & J#)

C# Tutorial : Lesson 7 - Creating Value Types & Reference Types - Part II

turbopowerdmaxsteel
foreach statement

This statement is explicitly used to traverse through arrays. The benefit of using foreach over the normal for statement is that it is not needed to check the size of the array while using the former.

Syntax:-

foreach(type identifier in expression)
{
statement 1;
statement 2;
....
}

Suppose we have an array StudentNames containing the name of all the students in a class. We need to display the name of each one of them on screen. First we will see how it can be done using the for loop.

CODE
string[] StudentNames = new string[] {"Peter", "Tony", "Bruce", "Scott", "Clark", "Kenshin"};
    for (int I = 0; I < StudentNames.Length; I++)
    {
        Console.WriteLine(StudentNames[I]);
    }


Now we'll use the foreach statement to do this.

CODE
string[] StudentNames = new string[] {"Peter", "Tony", "Bruce", "Scott", "Clark", "Kenshin"};
    foreach (string StudentName in StudentNames)
    {
        Console.WriteLine(StudentName);
    }


Param Arrays

Remember the Console.WriteLine method which outputs the result using a string format followed by the additional values as input parameters. For example: Console.WriteLine("The sum of {0} and {1} is {2}", Num1, Num2, Num1 + Num2); would display The sum of 5 and 6 is 11 for values 5 and 6 for Num1 and Num2 respectively. What is worth noting here, is that WriteLine() can take any number of parameters after the string format. So, something like this would work as well:-

Console.WriteLine("The Prime Numbers -> {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}", 2, 3, 5, 7, 11, 13, 17, 19, 23);

This is done by the param array data type. Example:-

CODE
public static int Sum(params int[] Numbers)
    {
        int Sum = 0;
        foreach (int Number in Numbers)
        {
            Sum += Number;
        }
        return Sum;
    }


This is a function to return the sum of any number of numbers. The numbers to be summed are passed as parameters during the function call as: Sum(4, 69, 13, 99);

Note: param array should be the last parameter in the function signature which also means that only one param array can be used in a function. Why is this done? Consider the following function signature: public static int MyFunction(params int[] A, int C). How would we call the function if this were to be allowed? MyFunction(1, 2, 3, 4, 5); How can the compiler determine where the values for the param array A finish? Actually, if a reverse scanning of parameters were to be done, this could be determined. But that would increase useless complexity of having to implement this along with the normal forward scanning of parameters.

Multi Dimensional Arrays

Up until now, we have only worked with Single Dimensional arrays. Now we shall see how the Multi Dimensional arrays are declared, initialized and manipulated. The pictures below show how the Single and Double Dimensional arrays are represented.





While, the Single Dimensional arrays are represented as a single row of elements, Double Dimensional arrays are represented by multiple rows. Similarly, arrays with 3 dimensions would be represented in 3D space along the three axes.

Declaration

Declaration is done by the syntax:-

datatype [ , ] VariableName;

The number of commas ( , ) inside the square brackets [ ] should be one less than the number of dimensions required for the array.

Example Usage:-

int [ , ] Numbers;

Initialization

Initialization is done in a way where each row is treated like a single dimensional array. Example:-

CODE
int[,] Numbers = new int[3, 3]
    {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };


Assigning Values

Values can be assigned as:-

Numbers[1, 2] = 7;

Array Class

The Array class defined in the System namespace serves as the base class for all the arrays in the Common Language Runtime. It can be used to create, manipulate, search and sort arrays.

Some of the common Properties and methods are summarized below.

Properties
  • IsFixedSize - Returns a boolean value (True / False) indicating whether the array is of Fixed Size or not.
  • IsReadOnly - Returns a boolean value (True / False) indicating whether the array is Read Only or not.
  • Length - Returns a 32-bit integer that represents the total number of elements across all dimensions in the array.
  • Rank - Returns the number of dimensions (also called the Rank) of the array.
Methods
  • BinarySearch - Performs the faster Binary Search algorithm on the array and returns the number if found.
  • Clear - Resets the value of the supplied range of elements in the array to the default values of the datatype:-
    • int - 0
    • bool - false
    • Reference Data Types - Null
  • Copy - Copies a range of elements to another array along with type casting and boxing as required
  • CopTo - Copies all elements to the specified single dimensional array
  • Find - Searches for the given value and returns its first occurrence in the array
  • FindAll - Returns all occurrences of the searched element in the array
  • GetLength - Returns the 32 bit length of the array
  • GetValue - Returns the value of the specified item in the array
  • IndexOf - Searches for the given value and returns the index of the first position its found in
  • Resize - Resizes the array
  • Reverse - Reverses the order of the elements. (Works only on a single dimensional array)
  • SetValue - Sets the value at the specified location of the array
  • Sort - Sorts the elements. (Works only on a single dimensional array)
Collections

An integer array can only store integers. Same goes for any other array type - string, boolean, etc. Collections overcome this limitation of arrays and can store elements of different types as items. This is possible because Collections actually store references and not values. We use the System.Collections namespace to work with collections.

Boxing - No, not the Sport! Boxing is the automatic conversion of value types to reference types allowing them to be stored in collections.
Unboxing - The reverse of the former, conversion of reference type to value type.

Because Collections store references, it is necessary to do the above conversions while storing and retrieving values in Collections.

List of classes under the System.Collection namespace.

Array List - Array List is a better alternative to arrays because of the following advantages it offers over arrays.
  • Resizing - Arrays cannot be resized natively. So, one has to create a new array and copy the elements of the existing one followed by rearrangement of references for this process. Array List on the other hand work on the concept of Linked List where memory is allocated and deallocated at runtime as and when required.
  • Adding an element - To add an element we need to first create a new array, copy the values before the position where the new element is to be inserted, insert the new element and then insert the remaining elements. Again, a cumbersome process for arrays. Array Lists only need to allocate memory for the new element and resolve the references of the elements on both side of the new element.
  • Deleting an element - All elements after the element to be deleted need to be shifted forward to fill up the vacancy created by the deletion. Array Lists rely on releasing the memory occupied by the element and resolving the references of the elements on both sides.
Common Methods used by the Array List class:-
  • Add - Adds an item at the end of the Array List
  • Clear - Removes all the items from the Array List
  • Insert - Inserts an element into the Array List at the specified position
  • Reverse - Reverses the order of all the elements or a portion of the Array List
  • Remove - Deletes the item at its first occurrence
  • TrimToSize - Sets the maximum capacity to the number of elements currently in the the Array List
Other Classes that the collection namespace provides are:-
  • Queue - A Collection that works on the First-In-First-Out (FIFO) rule. Here, insertion of elements occur at the rear and deletion at the front.
  • Stack - Works on the Last-In-First-Out (LIFO) rule. Both insertion and deletion occur at the top of the stack.
  • Hash Table - It uses unique keys to access/store elements in the collection.
Previous Tutorial - Lesson 6 - Creating Value Types & Reference Types - Part I

Lesson: 1 2 3 4 5 6 7

 

 

 


Reply

raghav_khunger
Awesome Tutorial!

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.

Recent Queries:-
  1. foreach and switch (c# reference) for string type - 0.73 hr back. (1)
  2. multidimensional array c# with random numbers - 8.94 hr back. (3)
  3. c# multidimensional changing value - 13.69 hr back. (1)
  4. how to store ref type in list - 14.20 hr back. (1)
  5. sum of numbers c# loop - 14.35 hr back. (1)
  6. c# check value 0-9 - 17.16 hr back. (1)
  7. creating properties with multiple values in c# - 23.53 hr back. (1)
  8. how to store two column values in arraylist in c# window application - 23.94 hr back. (1)
  9. store a reference in a array in c# - 24.08 hr back. (1)
  10. store the value in array list c# - 24.34 hr back. (2)
  11. c# get values from array - 32.89 hr back. (1)
  12. can we create a muliti dimensional hash table in vb.net - 33.88 hr back. (1)
  13. c# arrays value type or reference type - 36.10 hr back. (1)
  14. how to sum array values in c# - 36.71 hr back. (1)
Similar Topics

Keywords : c, tutorial, lesson, 7, creating, types, and, reference, types, part, ii

  1. Creating Your First Application
    (1)
  2. C# Tutorial : Lesson 9 - Constructors & Destructors
    (0)
    The need for Initialization A class contains data members (variables) and member
    functions. Initializing the values of these data members is essential, at times. Take a look at the
    following scenarios:- CODE int MyNumber; Console.WriteLine("My Number = {0}", MyNumber);
    This block of code declares a variable MyNumber and then prints it on the screen. However, when
    you try to execute these instructions, an error Use of unassigned local variable 'Product'
    will be generated. This is because, we are trying to use the value of MyNumber , even be....
  3. C# Tutorial : Lesson 8 - Functions/methods
    (0)
    The programming model has gone through many refinements, each change improving upon the model. One
    of the early changes was the inclusion of Subroutines or Subprograms. As the names suggest, these
    are fragments of code within a program. They offer the following advantages:- Reduction of code
    duplication by offering re-usability Simplifying program logic by decomposing the program into
    smaller blocks Improving readability of the program Why do we need functions?
    Consider the following program:- CODE using System; namespace ConsoleApplication1 { ....
  4. C# Tutorial : Lesson 6 - Creating Value Types & Reference Types - Part I
    (0)
    Value Types & Reference Types In C#, Variables are either value types or reference types
    depending on what they store, values or references. By reference we imply that the variable holds
    the memory address of another location where the actual value is stored. All built in data types -
    Int, Char, String, Float, Boolean, etc are value types while classes are reference types. The
    following is a diagrammatic representation of these two types. In this picture there are two
    variables Num1 and Num2. Both of these being integer variables store the values directly.....
  5. C# Tutorial : Lesson 5 - Encapsulation & Abstraction
    (0)
    Encapsulation & Abstraction Two concepts that go together in the object oriented approach
    are Encapsulation & Abstraction. Abstraction is the representation of only the essential features of
    an object, while Encapsulation is the hiding of the non-essential features. Think of a person
    driving a car. He does not need to know the internal working of the engine or the way gear changes
    work, to be able to drive the car (Encapsulation). Instead, he needs to know things such as how much
    turning the steering wheel needs, etc (Abstraction). Consider the example from ....
  6. C# Tutorial : Lesson 4 - Object Oriented Programming
    (2)
    Object Oriented Programming Object Oriented Programming is a methodology modeled on real
    life. It comprises of the basic unit, an object, being used in implementing a program. Think of all
    the objects around you - cars, buses, birds, trees, etc. You will find countless ones of them,
    everywhere you go. In order to tackle this huge number, we started classifying them, thus came the
    term Class. Class A class is a composition of the theoretic characteristics (attributes and
    properties) of an object and the things it can do - behaviors, methods and features. Tak....
  7. C# Tutorial : Lesson 3 - Programming Constructs
    (1)
    Conditional Branching By branching we imply, having different paths for execution.
    Conditions are used to determine which statements need to be executed. Suppose, you have a program
    to store the details of employees. Depending upon the post of the employee, there would be various
    fields associated with it. A department head, for example, would have a property denoting the
    department he heads, etc. We use conditional branching in such a scenario. C# provides the
    following conditional constructs:- if .. else Syntax:- if ( ) { statements } else { statement....
  8. C# Tutorial : Lesson 2 - Variables & Operators
    (0)
    Variables A Variable is a named location that stores a value. Although variables are
    physically stored in the RAM, their actual memory address is not known to the programmer. We can use
    the variables via the name we give them. These are the rules for naming a variable:- The name must
    begin with a letter or an underscore & can be followed by a sequence of letters (A-Z), digits (0-9)
    or underscore (_) Special Characters such as ? - + * / \ ! @ # $ % ^ ( ) { } , ; : . cannot be
    used in the variable name. A variable name must not be the same as a reserved k....
  9. C# Tutorial : Lesson 1 - Hello World Program
    (0)
    This is the first installment of my venture to explain the bits and pieces of C# that I have managed
    to learn at NIIT. In this lesson we would be creating the Hello World application. STEP 1 : Create
    a New Console Application in Visual C# The IDE automatically adds the following code:- CODE
    using System; using System.Collections.Generic; using System.Text; namespace HelloWorld {
        class Program     {         static void Main(string args)         {         }     } } Lets
    take a look at the first 3 lines. All of these lines begin with the keyword using....
  10. Installing Vb.net
    Part 1 - Obtaining, installing, and creating your first application (3)
    Well I didn't see anything on here about how to get started with vb .net, so I figured that I
    would write a small tutorial on how to get started with programming in VB .Net. If I get a lot of
    positive responses, I'll continue, if not I won't. Step 1: Obtaining Visual Basic .NET
    Microsoft in recent years has made a giant step in allowing hobbyists to learn program without
    having the burden of buying expensive software. This is a great business idea on their part, because
    it allows more people to become interested in their software, therefore, increasing th....
  11. Lesson #3 - Basic Math Operators And Random #s
    Lesson #3 - Basic Math Operators and Random #s (0)
    In this lesson I will cover how to use basic math operations, well addition really but you can also
    use subtraction , division and multiplication . I would also like to note that when doing
    division, if variabes of int type are used you will not get any remainders (i.e. n.345984). To be
    able to work with real numbers, numbers with decimals, you can use float. Below is a way to declare
    a float and assign it a value: float floatNumber; float Number = 28.47f; Aside from
    generating random numbers and basic math operations, we will also incorporate an if statement a....
  12. Lesson #2 - Switch Statement In C#
    Using the Switch Statement in C# (1)
    In the previous lesson we demonstrated did a basic input output application which asked your your
    name and replied with a general greeting using the name you entered. In this lesson we are going
    to learn about a conditional statement called the switch statement. Usually if and if else
    statements are taught before switch statements. Although these are very useful, I find the switch
    to be easier and more fun to use. The program written below is very similar to the previous
    program where the user is asked to enter their name, however now the program will loo....
  13. Lesson #1 - Introduction To C#
    Console Application (1)
    This tutorial will help get you started with C# Sharp. These tutorials will assume that you are
    using the Visual Studio environment. If you are just curious to test out some code, then you can
    copy and paste this code into your CS file, however, before doing so, make sure to name your project
    the same as the namespace on the code. But since this first program is fairly easy, it will not
    hurt to type it out. It is fairly easy and short. Also, this program is highly commented so it
    should be easy to follow along. Comments will have 2 forward slashes before them '....

    1. Looking for c, tutorial, lesson, 7, creating, types, and, reference, types, part, ii






*SIMILAR VIDEOS*
Searching Video's for c, tutorial, lesson, 7, creating, types, and, reference, types, part, ii
advertisement




C# Tutorial : Lesson 7 - Creating Value Types & Reference Types - Part II



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE