C Sharp/Variables

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Main Home

Basics
C# Tutorial Home
C# - Introduction to Visual Studio IDE
Introduction to C#
C# - Overview
C# - Statements
C# - Data Types
C# - Variables

C# - Operators
C# - Flow Control
C# - Variables II
C# - Functions and Methods
C# - Classes and Objects I
C# - Enumerations
C# - Dates and Times
C# - Random Numbers

Advanced
C# - Inheritance
C# - Polymorphism
C# - Garbage Collection
C# - Operator Overloading
C# - Encapsulation
C# - Properties
C# - Indexers
C# - Exceptions
C# - GUI
C# - Delegates
C# - Events
C# - Components
C# - Multithreading
C# - Regular Expressions
C# - Graphics and Multimedia
C# - Files and Streams
C# - XML
C# - Database, SQL and ADO.NET
C# - ASP.NET Web Forms and Web Controls
C# - Web Services
C# - Network Programming
C# - Datastructures and Collections
C# - Enumerations and Iterators
C# - .NET Assemblies
C# - CLR
C# - Visual Studio Debugger
C# - Namespaces
C# - Generics
C# - MS Intermediate Language
C# - Deploying Windows Application

[edit] C# Variables

A variable can be created by giving it a type and name(identifier). Variables can be initialized with a default value or can be initialized without being assigned a value.

int var1;
  • int is the type
  • var1 is the identifier or the name of the value


char value1;
  • char is the type
  • value1 is the identifier or the name of the value


Lets take a look at some code:


  1. using System;
  2.  
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. int a; //Declare a variable
  8.  
  9. a = 3; //Initialize 'a' with a value of 3
  10. Console.WriteLine(a); //Print the variable
  11. Console.Read();
  12. }
  13. }

Output

3


  • Line 7: declares a variable a of type int.
  • Line 9: initializes the variable a with the value 3.
  • Line 10: prints the value in variable a.

Run the code above

[edit] Declare a variable and initialize it

int var1 = 91;
  • var1s type is int with a value of 91
char value1 = 'c';
  • value1s type is char with a value of c.


Example code

using System;
 
class Program
{
    static void Main(string[] args)
    {
        int a = 23;
        char b = 's';
 
        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.Read();
    }
}

Output

23
s


Run this code.

[edit] Declare multiple variables

You are able to declare multiple variable on one line. Here is how to do it:

int var1 = 3, var2 = 78, var3, var4 = 0;
  • Notice: var3 is not initialized. Before you can use it you must initialize it first.
char value1 = 'z', value2 = 'a', value3, value = 'e';
  • Notice: value3 is not initialized. Before you can use it you must initialize it first.


int var1 = 3, char var2 = 'w';
  • Notice: you can only use the same types. Do you see int with char? This is an error.
Personal tools