Variables, Constants & Type Conversion

লেসন ২ / ৫০

Variable Declaration

// Explicit type
int age = 25;
string name = "Rahim";

// Implicit (var) — compiler type infer করে
var count = 100;          // int
var price = 99.99m;       // decimal
var items = new List<int>();

const vs readonly

// const — compile time, primitive only
const double PI = 3.14159;
const string APP_NAME = "MyApp";

// readonly — runtime এ একবার assign
class Config {
    public readonly string DbConnection;
    public Config(string conn) {
        DbConnection = conn;   // constructor এ assign OK
    }
}

Type Conversion

// Implicit (safe, smaller → larger)
int i = 100;
long l = i;
double d = i;

// Explicit cast (data loss সম্ভব)
double pi = 3.14;
int rounded = (int)pi;    // 3

// Convert class
string num = "42";
int n = Convert.ToInt32(num);
double dd = Convert.ToDouble("3.14");

// Parse & TryParse (safer)
int result;
if (int.TryParse("123", out result)) {
    Console.WriteLine($"Parsed: {result}");
} else {
    Console.WriteLine("Invalid number");
}

// C# 7+ inline declaration
if (int.TryParse(input, out int val)) {
    Console.WriteLine(val);
}

Nullable Value Type

int? age = null;          // nullable int
if (age.HasValue) {
    Console.WriteLine(age.Value);
}

// Null-coalescing
int actual = age ?? 0;    // null হলে 0

Boxing/Unboxing

int x = 42;
object o = x;            // boxing (stack → heap)
int y = (int)o;          // unboxing
// Performance hit — যতটা সম্ভব এড়ান