Declaring Variables in Visual Basic .NET and C#

Now that you have an understanding of the CLS-compliant data types in .NET, you need to learn how to use these types in your code by declaring variables. You use a declaration statement to define a variable; you also can optionally set a value for the variable when you declare it.

Note

Today, you won't create an application and follow along. You use the code in the listings throughout the day as part of your exercises at the end of the day. If you want to test the code as you're reading, you can create a Windows Forms application and add the various code listings to the code-behind for button click events.


In Visual Basic .NET, using the Dim statement is the simplest way to declare a variable. The following code declares a variable named intX as the data type Integer:

Dim intX as Integer

The format for declaring a variable in Visual Basic .NET is

						Scope variable_name as DataType
					

The Scope of the variable defines where the variable can be accessed, the name is the descriptive name that you give the variable, and the DataType is any of the CLS-compliant types listed earlier in Table 8.1.

In C#, the format is almost identical, just reversed. The following code declares a variable named intX as the C# data type int:

int intx;

Where the format is

						Scope DataType variable_name;

Note

Remember that C# is a case-sensitive language. If you declare variables named intX, INTX, IntX, and intx, you'll have four separate variables. In Visual Basic .NET, they would all be considered the same variable because Visual Basic .NET isn't a case-sensitive language.


In C#, all statements are followed by the semicolon. So, a semicolon must follow a variable declaration, and anything after the semicolon is considered another statement to be checked by the compiler.

In both Visual Basic .NET and C#, you can declare multiple variables in a single statement, as the following code demonstrates:


Dim intX, intY, intX as Integer



int intX, intY, intX;

In both examples, the data types for each variable are the integer data type. In Visual Basic .NET, you can specify multiple variables on the same line with different data types. The following code shows the declaration of two variables—one integer and one string:

Dim intX as Integer, Dim strName as string

You can also set the value of a variable when you declare it. The following code sets the value of the intX and intY variables, but not the intZ variable:


Dim intX As Integer = 5, intY = 10, intZ



int intX = 5, intY = 10, intZ;

Understanding Variable Scope

When you declare a variable, you can optionally declare it with an access modifier, which specifies where the variable can be accessed by other elements within your application. This is called the scope of the variable.

In C#, the access modifiers are

  • public— Access is available to any other class or class member in the same project, another referenced project, or another referenced assembly.

  • protected— Access is limited to the containing class or types derived from the containing class.

  • internal— Access is limited to the current project.

  • private— Access is limited to the containing type.

In Visual Basic .NET, the access modifiers are

  • Public— Access is available to any other class or class member in the same project, another referenced project, or another referenced assembly. At the class level, using Dim is the same as using Public.

  • Protected— Access is limited to the containing class or types derived from the containing class.

  • Friend— Access is limited to the current project.

  • Protected Friend— Access is limited to derived classes or the same project. This can be used only at the class level when declaring variables, not at the procedure level.

  • Private— Access is limited to the procedure, class, or structure.

In Listing 8.1, you can see the usage of the different access modifiers. Read the comments within the code to see where the variables can be used.

Listing 8.1. Implementing Different Access Modifiers for Variables and Classes
' Public Class variable accessible to
' any object that derives from this class
Public Class Class1

   ' Public to this class and any class that derives from this class
   Public strName As String

   ' Private to this class only
   Private intX As Integer

   ' Accessible from any class in the project
   Friend intZ As Integer

   ' Private Sub Procedure available to Class1, and NOT
   ' any classes that derive from Class1
   Private Sub Test()

      ' Private to the procedure Test()
      Dim intX As Integer

   End Sub

   ' Public Sub Procedure available to Class1, and
   ' any classes that derive from Class1
   Public Sub TestPublic()

   End Sub

End Class
						

// Public Class variable accessible to
// any object that derives from this class
   public class Class1
   {

      // Public to this class and any class that derives from this class
      public string strName;

      // Private to this class only
      private int intX;

      // Accessible from any class in the project
      internal int intZ;

      public Class1()
      {
         // Add constructor code here
      }

      // Private Sub Procedure available to Class1, and NOT
      // any classes that derive from Class1
      private void Test()
      {
         // Private to the procedure Test
         int intX;
      }

      // Public  Procedure available to Class1, and
      // any classes that derive from Class1
      public void TestPublic()
      {

      }

   }

Using Constant Variables

A constant is an access modifier that enables you to declare a variable whose value doesn't change throughout the lifetime of your application. The best example of a constant is the value of PI, which is a long number that you might not want to type every time you use it in a mathematical application. The following code declares a constant for the value of PI using the Const keyword:


Const myPI As Decimal = 3.4799897



const decimal myPI = 3.4799897;

After you declare a constant, you cannot modify its value at runtime. That means the constant's value remains the same for the lifetime of your application.

Using Static and Shared Variables

Static and shared variables are special variable types that retain their values. In C#, the keyword Static is equivalent in function to the Visual Basic .NET keyword Shared. When you declare a variable as Static in C# and Shared in Visual Basic .NET, the variable's scope is public or private to the class that it's in, but isn't affected by instances of the class.

For example, when you declare a variable as a type of a specific class, you have access to the class's members, such as public, protected, and friend procedures and variables. If a member of the class is defined as Static in C# or Shared in Visual Basic .NET, the member is specific to the class, not an instance of the class.

The code in Listing 8.2 uses a globalCounter variable and an Increment method that aren't affected by the creation of any new instances of the StaticTest class.

Listing 8.2. Using Shared/Static Variables in a Class
Public Class StaticTest

   Public Shared globalCounter As Integer

   Public Shared Function Increment() As Integer

      globalCounter += 1
      Return globalCounter

   End Function

End Class

public class StaticTest
{
   public StaticTest ()
   {
   }


   public static int globalCounter;

   public static int Increment()
   {
      return ++globalCounter;
   }
}

Now declare an instance of StaticTest, as this Visual Basic .NET code demonstrates:

Dim x As New StaticTest()
Dim c As Integer = x.Increment()
MessageBox.Show(c.ToString)

Dim y As New StaticTest()
c = y.Increment()
MessageBox.Show(c.ToString)

Each separate instance of the StaticTest class retains the value of the globalCounter variable. It's shared across all instances of the class.

Using the New Keyword

The New keyword in Visual Basic .NET and the new keyword in C# are used to create new object instances. In some of the code you've seen today, New was used to demonstrate the creation of an instance of a class. Each class file in your project contains members, which are simply the methods, variables, properties, and structures that make up the class. To use a class's members, you must create a variable of the type of class you're trying to work with.

Note

This book isn't a lesson on object-oriented programming, and you won't get too heavily into creating your own custom classes. But it's important to understand terms such as type and members. Earlier, you saw the list of CLS-compliant data types. Each of those data types is simply a type in the FCL. When you declare a variable as an integer, you can say that you've declared a variable of type integer. Each time you create a new class file in your projects, you're creating a new type. By adding properties, methods, structures, and variables to the class, you're creating the members of the class. When an instance of the class is created, it's simply another type to be managed by the common language runtime.


When you use the New keyword, you're creating a variable of a specified type and setting its members to their default values. In the case of a base type, such as an integer, creating a new instance of a variable of type integer defaults the variable's value to zero. In the case of a class, all nonstatic or nonshared variables are set to their default values. The New keyword is used all the time in .NET. Because you're writing code in class files, you must normally create an instance of that class before you attempt to access any of its members. The following code creates a new instance of Class1 and makes it available to the variable X:


Dim x as Class1 = new Class1
' Both of these declarations are equivalent in VB.NET
Dim x as new Class1



Class1 x = new Class1;

After you've declared X as a new instance of the class Class1, you have access to the members of Class1 using the dot notation. For example, if Class1 has a public string variable named firstName, you can access it as follows:


'  Set the variable
x.firstName = "Jason"

' Retrieve the variable
MessageBox.Show(x.firstName)



//  Set the variable
x.firstName = "Jason";

// Retrieve the variable
MessageBox.Show(x.firstName);

Each time you use the New keyword, you're creating an instance of a class. The variable holds the instance, which then has access to all the members in the class instance you've declared.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.151.45