Braintique.com header
Left Navigation Bar

C# Variables

A variable combines a type with a way to store a value of the specified type. (I discuss types later in this article, but you are certainly already familiar with some of the C# types, such as int [integer] and string.) The value of a variable can be assigned, and that value can also be changed programmatically at any point.

A variable is created in C# by declaring its type and then giving it an identifier. For example:

int theInt;
string deeFlat;

The variable can be initialized, meaning given an initial value, at the time it is declared—although this is not required. Here are the same variables declared and initialized:

int theInt = 42;
string deeFlat = "This is a string!”;

Alternatively, of course, with the same effect, you could declare the variables and later assign them values:

int theInt; string deeFlat;
...
theInt = 42;
deeFlat = "This is a string!”;

To digress for a second here: you may not know that even simple value types such as int inherit from object. This implies that you could declare an int (or other value type) variable using the new constructor. So

int i = new int();

is the equivalent to the standard int declaration:

int i;

One thing you should know is that C# requires that variables be assigned a value—either through initialization or programmatic assignment—before they are used. This is known as definite assignment and codifies what is good practice in any case. As they say, an uninitialized variable is like an unmade bed—you never know what you’ll find in it. For example,

string unMadeBed;
MessageBox.Show(unMadeBed, "Hello, Variables!",
MessageBoxButtons.OK);

produces a syntax error and will not compile because of the attempted use of an unassigned variable.


Previous Table of Contents Next


Google
 
Web www.braintique.com
www.digitalfieldguide.com www.googleplexblog.com


Home | Barticles | Blogs | Books | Services | FAQ | Contact

© Braintique.com. All rights reserved.

Search Engine Optimization







RSS 2.0 Syndication feed

Syndication Viewer

Our Web host:
IX WebHosting



Food for Your Brain! Get a Barticle! Questions Answered Books for You What We Can Do For You Contact Us Brain Food Questions Answered Books for You What We Can Do For You Frequently Asked Questions About Us Google Research Photoshop Wi-Fi and Wireless Networking The Natural Way to Write