using System;
namespace VariableExample
{
class Program
{
static void Main()
{
// Value Types
int age = 21;
double price = 199.99;
bool isStudent = true;
// Reference Types
string name = "Megha";
int[] numbers = { 1, 2, 3, 4, 5 };
// Output
Console.WriteLine("Value Types:");
Console.WriteLine("Age: " + age);
Console.WriteLine("Price: " + price);
Console.WriteLine("Is Student? " + isStudent);
Console.WriteLine("\nReference Types:");
Console.WriteLine("Name: " + name);
Console.WriteLine("Numbers Array: " + string.Join(", ", numbers));
}
}
}
Value Types:
Age: 21
Price: 199.99
Is Student? True
Reference Types:
Name: Megha
Numbers Array: 1, 2, 3, 4, 5
This example demonstrates both value types and reference types in C#:
- Value Types:
int
, double
, bool
store actual data.
- Reference Types:
string
, array
store the memory address of the data.
- Output: Displays both types separately for clarity.
- string.Join is used to print array elements neatly.
Best Practices:
- Use meaningful variable names (
age
, name
, numbers
).
- Keep value and reference types organized for readability.
- Always initialize variables before using them.
Using Visual Studio:
- Open Visual Studio.
- Go to File → New → Project → Console App.
- Paste the code in Program.cs.
- Press F5 to run → Output appears in the console.
Using Command-line:
- Save file as
VariableDemo.cs
.
- Open Command Prompt and navigate to the file directory.
- Compile:
csc VariableDemo.cs
- Execute:
VariableDemo