Skip to main content

Value Type Parameter in C#

As mentioned previous chapter, there are two types of parameter that can be passed in function. One is Value type parameter and another is reference type parameter. Before understanding both type of parameter in C#, you will have to understand Value type and Reference type.
There are two ways to allocating space in memory. One is value type and another is Reference type. When you create int, char or float type variable, it creates value type memory allocation whereas when you create object of class, it creates reference type memory allocation.


Value Type: A value type variable directly contains data in the memory.

Reference Type: A Reference type variable contains memory address of value.

Consider the following graph to make better sense of value type and reference type.

int Result;
 result=200;





In the preceding example, the value type variable contains the value whereas a reference type variable contains the address of Result variable.

Value Type Parameter:

 In value type parameter, the actual value gets passed to the function. Passing a value type variable as parameter means, you are passing the copy of the value.

Example:


using System;

namespace Value_Type
{
  class Program
   {
     public static int qube(int num)
      {
        return num * num * num;
      }
     static void Main(string[] args)
      {
        int val,number;
        number = 5;
        //Passing the copy value of number variable
        val = Program.qube(number);
        Console.Write(val);
        Console.ReadLine();
      }
   }
}


Output

125





 

Comments

Popular posts from this blog

C# Array

Array is a collection of variable of same data type. If you have declare 1000 integer variable, then you can declare an integer type array of 1000 size. The value of array can be accessed using index position of array. The first index position of array is zero. In C#, there two types of array: Single Dimensional Array and Multi Dimensional Array. You can use both type of array easily and can access its element using loop constructs or index position.

Structure (C#)

Structure is the value type data type that can contain variables, methods, properties, events and so on. It simplifies the program and enhance performance of code in C# programming. The structure encapsulate small group of related variables inside a single user-defined data type. It improves speed and memory usage and also enhances performance and clarity of your code. How to use structure in C#? It is very simple to use structure in C#. The following programming example will show you to how to create and use structure in C# programming. Programming Example of Structure (C#) using System; namespace Structure {    class Program    {      // creating three different variable in single structure       struct book        {          public string bookname;          public int price;          public stri...