Author Topic: Introduction to C# variables  (Read 522 times)

0 Members and 1 Guest are viewing this topic.

Offline ShadowCloud

  • Serf
  • *
  • Posts: 33
  • Cookies: 31
  • -My word is my bond
    • View Profile
Introduction to C# variables
« on: November 27, 2015, 06:18:21 am »
C# – Variables

C# is a type safe language, that means that variables only hold certain types of values and that the compiler guarantees that you have a valid type as the value for the variable.  It is extremely important to know that a value must be definitely assigned before its value can be obtained, or used, in your program.
The value held in a variable is either initially assigned or assigned through an assignment statement, which is really just a fancy way of saying we give it a value like:  x = 5;

In an application that has a membership class (user management) you could create a class for users with the following properties:

Username
Password
Join date
Last Login date
Active
Locked Out
FailedPasswordAttempts

Your site will most likely have multiple users, so in that case your member class will be an instance class, meaning, you create several instances in your code, all of these will use the same connection class to retrieve, update and insert new members.

Getting practical

We’ll be using a small class I’ve adapted from  MSDN to go through the different variable types:

Code: [Select]
class AnotherClass
    {
        public static int x;
        int y;

        public void ChangeValues(int[] v, int a, ref int b, out int c)
        {
            int i = 1;
            c = a + b++;
            Console.WriteLine("x is : " + x);
            Console.WriteLine("y is : " + y);
            Console.WriteLine("v is : " + v);
            Console.WriteLine("b is : " + b);
            Console.WriteLine("c is : " + c);

        }
    }

Before we drill down into that, let’s have a look at the different types of variables we have:

x is a static variable, y is an instance variable, v[0] is an array element, a is a value parameter, b is a reference parameter, c is an output parameter, and i is a local variable.

Here you can see our class, AnotherClass is an instance class, it is not a static class.  However, the variable x has been declared in a static context, which means we don’t need to instantiate an instance of the class before we have access to x.

Here it might be more apt to explain static in a slightly different example:  Think of the blueprints for the houses in a housing complex, they are all built the same.  This means that the blueprint is static, but each house is an instance of that blueprint. 

We’ll be instantiating an instance of the class above shortly, which should make things a bit clearer.

So straight from MSDN:
“Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.”

If you’re still a bit confused on this subject feel free to take a look at:  http://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.80%29.aspx

y is an instance variable, which means that each instance (or each house) can have a different value for y, while they all shared the same value for x.

v is an array element of type int.  Which means it holds multiple int values.  Arrays are identified by the “[]” specified right after the type declaration.
The following 3 types are used whenever variables are used across different methods or classes.

1) Value Parameter
Remember that when you specify variables when creating a method those are called parameters, when you call the method you created and specify the data to use for those variables, they are called arguments. 

The default type is a Value parameter:  This simply gives the value held in the variable to the method.  The original value we used as an argument remains unchanged.  This type of parameter is declared by not specifying ref or out keywords.

2) Ref Parameter
A parameter declared with a ref modifier is a reference parameter.
A reference parameter does not create a new storage location. Instead, a reference parameter represents the same storage location as the variable given as the argument in the function member invocation. Thus, the value of a reference parameter is always the same as the underlying variable.
3) A parameter declared with an out modifier is an output parameter.
An output parameter does not create a new storage location. Instead, an output parameter represents the same storage location as the variable given as the argument in the function member invocation. Thus, the value of an output parameter is always the same as the underlying variable.

From the above you can see that ref and out appear to be exactly the same, but there are some differences you need to note, out parameters do not need to be initialized. So what does that mean to us?  Whenever you will be using the value of a parameter in the method and the initial value will affect the outcome of the method you need to use ref.  Whenever the outcome is not affected by the value of the parameter, use out. 

To sum that up, if your value does not need to be returned, use a value parameter.  If the initial value is going to affect the outcome of the function, use ref.  If you just want the value returned in the end, use out.

So let’s get to something practical, create a new console application and type up the following:
   





So let’s go through that, remember that a C# program always starts at static void Main this is the entry point for the program.

Line 8 : Here we declare an array of type int.  This is your first introduction to arrays, so I’ll spend some time explaining it first.  Arrays are used to hold a sequence of values, rather than just one value.  A good example of an array of type would be file extensions for an upload field you can specify an extension in each element of the array.  It is important to note that arrays can be multidimensional but we’ll get to it later on, for now we’ll deal with linear (one dimensional) arrays.

In this line, I’ve specified the array size as 3, meaning it can hold 3 values.

Line 9-11 : Here I’ve assigned a value to each index in the array.  You’ll see that it starts at the index 0. 

Line 12-15:  Here I’ve used a for loop to cycle through all the values and display them.  I’d suggest you set a breakpoint and add loop through the lines to see the lines in action in the event that you don’t understand the output.  For anyone looking for more info on for loops see: http://www.dotnetperls.com/for
Line 16:  This is really where the magic happens.  This is where we instantiate an instance of the class AnotherClass.  This is like creating a new house from the blueprint.  To illustrate the static context again, I’m going to show you what is accessible before we instantiate the instance and then what’s available after instantiating an instance:

Before line 16:


   
Because x is static, we can access x anywhere. 
After line 16 : Now we’ve instantiating AnotherClass as “a” so if we do this on our instance of AnotherClass we have the following:



As you can see we now have access to the method ChangeValues on line 29.

Line 17 : Here we call the method we declared on line 17 and we specify the values or arguments we want to send to the function.  Remember that if the value influences the value the method will return, we use a ref parameter, if we purely want it to return the new value we use out:

Line 18-20:  This is just used to output the values again after our method has done what it needed to do.  Remember that from line 17 the code will go to line 30 and return to line 17 again once it reaches line 39.

The class itself is really simplistic and I’m not going to waste too much time explaining it.

You should see the following output:



Now as you can see, the value for v is a bit messed up, so we’ll spend some time fixing that next:
We have the output for what v is, it’s an array (indicated by the []) that holds values of the type int (System.Int32)

As an added bonus this is the decompiled reference to Int32:


 
As you can see there is quite a bit going on with an Int, but this all under the hood and there is no reason for us to delve any deeper into this atm.
Instead of seeing what v is, we want the program to show us all the values in contained inside the array called v.

Inside the array

To fix our little v problem, we need to go through all the elements in the array and display the value for each one of them.  We’ll use a for loop to cycle through it, similar to the for loop in our main method:
So we change line 35 to:
 


Based on that, you should get the following output:



If anyone has any questions on this or needs some help, feel free to PM me after you’ve Googled around a bit, the best way to find answers is still to play around with this yourself.  This lesson should give you a pretty good base to explore from.
QA Engineer walks into a bar. Orders a beer. Orders 0 beers. Orders 999999999 beers. Orders a lizard. Orders -1 beers. Orders a sfdeljknesv.