Type conversion is basically type casting or converting one type of data to another type. In C#, type casting has two forms:
- Implicit type conversion - these conversions are performed by C# in a type-safe manner. Examples are conversions from smaller to larger integral types and conversions from derived classes to base classes.
- Explicit type conversion - these conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.
The following example shows an explicit type conversion:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practice
{
class Program
{
static void Main(string[] args)
{
ConvertAndSize c = new ConvertAndSize();
c.conversion();
Console.ReadKey();
}
}
}
class ConvertAndSize
{
public void conversion()
{
double f = 33.33;
int i;
// cast
double to int.
i = (int)f;
Console.WriteLine(i);
}
}
Output:
33
No comments:
Post a Comment