ุนู†ุฏู†ุง ู†ูˆุนูŠู† ู…ู† ุงู„ Casting:

  • Implicit Castingย (automatically) - converting a smaller type to a larger type size
    charย โ†’ย intย โ†’ย longย โ†’ย floatย โ†’ย double
  • Explicit Castingย (manually) - converting a larger type to a smaller size type
    doubleย โ†’ย floatย โ†’ย longย โ†’ย intย โ†’ย char

Implicit Casting

No need of Casting

int myInt = 9;
double myDouble = myInt //Automatic casting: int to double
//Safe Casting , No RunTime Errors 

Explicit Casting

Memory

  • ุจูŠุญุตู„ ู…ุน ุงู„ unsafe castingุŒ ุงู† ู…ู…ูƒู† ุงู„ data type ูŠุดูŠู„ ุงู„ู‚ูŠู…ุฉ ุงู„ู„ูŠ ู‡ุฏูŠู‡ุงู„ู‡ ูˆู…ู…ูƒู† ู„ุง
  • ูŠุนู†ูŠ ุฃุญุงูˆู„ ุฃุญุท ุญุงุฌุฉ ูƒุจูŠุฑุฉ ููŠ ุญุงุฌุฉ ุตุบูŠุฑุฉ ููŠ ุงู„ memory ูู…ุด ู‡ูŠู‚ุจู„
int x = 5;
double y = 50;
 
x = (int) y;
 
Y = long.MaxValue;
x = (int) y; 
// overflow, but no error here, just garbage value
  • ููŠ ุญุงู„ุฉ ุงู†ูŠ ุงุฏูŠุชู„ู‡ ู‚ูŠู…ุฉ ู…ุชู‚ุฏุฑุด ุชุดูŠู„ู‡ ููŠ ุงู„ุญุงู„ุฉ ุฏูŠ ุงู„ CLR ู…ุด ุจูŠุฑู…ูŠ exception ูˆูŠูˆู‚ู ุงู„ุจุฑู†ุงู…ุฌ ูˆููŠ ุงู„ุญุงู„ุฉ ุฏูŠ ุงู„ exception unhandled ูˆุจูŠูุถู„ ูƒุฏุง ู„ุญุฏ ุงู…ุง ุจุนู…ู„ู‡ Cs Handle Exception
  • ุจูŠู…ู„ู‰ ุงู„ู…ูŠู…ูˆุฑูŠ ูˆุจุนุฏูŠู† ู„ูˆ ุฎู„ุตุช ูˆุนุงูŠุฒ ุฃูƒู…ู„ ุจุฑู…ูŠ ุงู„ู„ูŠ ููŠู‡ุง ูˆุฃุจุฏุฃ ุฃู…ู„ู‰ ุชุงู†ูŠ
int x = 300;
byte y = (byte) x; // byte -> 255
// 300 = 255 + 44

Checked

  • ุจูŠุทู„ุน Exception ู„ูˆ ุญุตู„ Overflow ููŠ ุงู„ุญุงุฌุฉ ุงู„ู„ูŠ ุจุฎุฒู† ููŠู‡ุง
  • ูˆููŠ ุงู„ู…ุณุชู‚ุจู„ ู„ูˆ ุนุงูŠุฒ ุชุนู…ู„ handling ุนุงุฏูŠ
int x = 300;
checked 
{
	byte y = (byte) x; // Unhandled exception. System.OverflowException
}

Unchecked

  • ูƒู„ ูุงูŠุฏุชู‡ุง ุงู† ู„ูˆ ุญุตู„ overflow ู…ูŠุฑู…ูŠุด exception ูˆู…ุด ุจูŠุชู… ุงุณุชุฎุฏุงู…ู‡ุง ุบูŠุฑ ู…ุน ุงู„overflow errors
  • ุจุณุชุฎุฏู…ู‡ุง ุฌูˆุง ุงู„ checked ุจู„ูˆูƒ ู„ูˆ ููŠู‡ ุฌุฒุก ุฌูˆุงู‡ ู…ุด ุนุงูŠุฒ ูŠุชุนู…ู„ู‡ check

Data Type

C# Method (Parse)

  • ู„ูˆ ุนุงูŠุฒ ุฃุบูŠุฑ ู…ู† ู†ูˆุน ู„ู„ุชุงู†ูŠ ูˆู‡ูˆ ู…ุด ุณุงู…ุญ ุจูƒุฏุง ุจุณุชุฎุฏู… Parse
int a = Console.ReadLine(); // String -> int : ERROR
 
int a = int.Parse(Console.ReadLine());
// All data types have that exept Strings
 
// ERROR
int x = 5;
string y = string.Parse(x);

.NET Method (Convert)

ู…ู…ูƒู† ู†ุบูŠุฑ ู…ู† ู†ูˆุน ู„ู†ูˆุน ุชุงู†ูŠ ุจุงุณุชุฎุฏุงู… ุดูˆูŠุฉ methods ูƒุฏุง Convert.ToBoolean,ย Convert.ToDouble,ย Convert.ToString,ย Convert.ToInt32ย (int) andย Convert.ToInt64ย (long)

int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
 
Console.WriteLine(Convert.ToString(myInt));    // convert int to string
Console.WriteLine(Convert.ToDouble(myInt));    // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble));  // convert double to int
Console.WriteLine(Convert.ToString(myBool));   // convert bool to string

Info

ุจุงู„ู†ุณุจุฉ ู„ู„ Convert ูููŠู‡ุง ู…ูŠุฒุฉ ู‚ูˆูŠุฉ ุฌุฏู‹ุง ูˆู‡ูŠ ุฅู† ู„ูˆ ุจุชุนู…ู„ convert ู„ int ู…ุซู„ู‹ุง ูˆุงู„ู‚ูŠู…ุฉ null ูู‡ูˆ ู‡ูŠุญุทู‡ุง ุจ zero ู‡ูŠู‡ู†ุฏู„ ุงู„ุฏู†ูŠุง ู„ูˆุญุฏู‡