Casting

CSharp · Console

/Program.cs

using System;

public class Program
{
	public static void Main()
	{
		long l = 2222;
		// use () operator to convert a type explicitly
		int i = (int)l; // Explicit casting from long to int
		
		
		// When we cast 786.78 into an integer, the resulting value is 786. 
		//The decimal portion is truncated after the conversion.
		double d = 786.78;
		// int i = d; // Incompatible Data Type
		
		// Explicit casting from double to int 
		int i1 = (int)d;   
		
		
		
		
		
		double d1 = 786.78;
		// Or
		//var d = 786.78;
		
		float f = (float)d1;
		decimal dec = (decimal)d1;

		
		Console.WriteLine($"i = {i}"); // Print 2222
		Console.WriteLine($"i1 = {i1}"); // Print 786
		Console.WriteLine($"f = {f}"); // Print 786.78
		Console.WriteLine($"dec = {dec}"); // Print 786.78
		
		
		Console.WriteLine("\n -----------InvalidCastException-----------");
		object val = "12";
		int i3 = (int)val;

	}
}
;