Nullable Types
- ูู ุนุจุงุฑุฉ ุนู value types ุจุชุณู
ุญ ุจุงู
null
ูุจููุถู ุฒู ู ุง ูู value type - ุจูุณุชุฎุฏู ูุง ูุชูุฑ ู ุน ุงู ReadLine ูุงู ู ู ูู ุงู user ู ูุฏุฎูุด ููู ุฉ ูุงูู ูุฑูุถ ุชุชุฎุฒู Null
- ูุนูู ู
ุซูุง ุงู
int
ู ุด ุจูุณู ุญ ุงูู ุชุญุทnull
ูููู ุฉ
int x = 50;
// x = null; // ERROR
int? Y; //Nullable int, IL (Nullable<int>)
Y = 5000;
Y = null;
ูู value type ูููุง ุงู nullable type ุจุชุงุนูุง ูุงู reference types ูุฏุง ูุฏุง ุจุชุณู ุญ ุจุงู null
Syntax Sugar
ูู ุนุจุงุฑุฉ ุนู syntax sugar ููCs Struct ุงุณู ู Nullable
int? x = 5; // Nullable<int>
x = null;
int? x = null;
Nullable<int> y = null;
Console.WriteLine(x);
Console.WriteLine(y);
ู
ููุด ููู ุบูุฑ ู
ุชุบูุฑูู ุงุชููู ุจุณ ููู
ุง HasValue
ู Value
ูุทุฑููุฉ ุดุบููุง ุจุจุณุงุทุฉ ุฅู ูู ูู ุจ null ูุจูุง ูุฏุง HasValue
ูุจูุง false ูู
ููุด ููู
ุฉ ูู ุงูู value ุฅูู
ุง ูู true ูุจูุง ูุฏุง ููู ููู
ุฉ ูู ุงูู Value
ูู ุฎุฏุช ุจุงูู ุจุงูุทุฑููุฉ ุฏู ูู ูุชูุถู value type ู
ุด ูุชุชุญูู ูู Reference ููุง ุญุงุฌุฉ
Casting
ุทุจุนูุง ุงุชุนูู ูุง ุงุฒุงู ูุนู ู Cs Type Casting ูุงูู ุงูููุนูู ุงููู ุนูุฏู ูุงููุฑู ุจูููู ุ ูุชุนุงูู ูุทุจู ููุง ูู ุนุงูุฒ ุฃุนู ููุง casting ุงูู ุงูู ุณู ูุญ ูุงูู ุงููู ูุง
int x = 50;
int? Y; //Nullable int
Y = null;
Y = X; // Safe Casting, Implicit (Small in Big)
X = Y; // UnSafe, Explicit: ERROR (Big in Small)
X = (int) Y;
Null Propagation (Conditional) Operator
ู ุนูุงูุง:
- ูู ุงููู ูุจู ุงูู ? ุจู nullุ ู ุชููุฐุด ุงููู ุจุนุฏูุง
ู
ุชุนู
ูุด call ูู length ูู ุงู arr
ุจ null
for (int i = 0; i < Arr?.Length; i++);
ู ู ูู ุฃุณุชุฎุฏู ูุง ุฃูุชุฑ ู ู ู ุฑุฉ ูุฑุง ุจุนุถ ุนุงุฏู ุนุดุงู ูุฏุง ุงุณู ูุง Propagation
class Dept
{
public string Name;
}
class Employee
{
public Dept Dept;
}
Empolyee E = default;
Console.WritLine(E.Dept.Name); // Unsafe
Console.WriteLine(E?.Dept?.Name??"Not Available");
ู ุซุงู ุขุฎุฑ
int R = Arr.Length; //Unsafe
int? RR = Arr?.Length; //Safe, Nullable int
//Arr?.Length === (Arr != null)? Arr.Length : null
int RRR = Arr?.Length??0; //Safe
Important Information
Default
ูู ู
ุด ุนุงุฑู ุงุฏู initial value ุงูู ุจุฏู ูู data type ููู
ุฉ default
double D = default;
int [] Arr = default; // null, default value for all reference types
NullReferenceExeption
ู
ู ุฃุตุนุจ ุงูู
ุดุงูู ุงููู ู
ู
ูู ุชูุงุจู ุฃู programmer ูู ุงู NullReferenceExeption
ุงูู ุจุญุงูู ุฃูุตู ูุญุงุฌุฉ ุจุชุดุงูุฑ ุนูู null
int [] Arr = default; // null
for (int i = 0; i < Arr.Length; i++)
Console.WriteLine(Arr[i]);
ูุนุดุงู ูุฏุง ูุงุฒู ุชุนู ู check ุนุดุงู ุชูุตู ูู ุฑุญูุฉ ุงู Cs Protective code
for (int i = 0; (Arr != null) && (i < Arr.Length); i++)
ุงููุฑู ุจูู && , &
&&: ุจูุดูู ุงูุฃูู ูู ู ุญููุด ุงูู ุทููุจ ุจูููู ุงูุจุฑูุงู ุฌ ูุนูู ููู ููู ุงูุฃูู ุจnull ูู ุด ูููู ู ุงูุชุงูู
&: ุฏู ุนุจุงุฑุฉ ุนู bitwise ููุงุฒู
ูุดูู ููู
ุฉ ุงูุงุชููู ููุนู
ููู
anding
ู
ุน ุจุนุถ