C# Convert

Convert class can handle data type conversions, it can be run at .NET Framework 4.5 and higher.

using System;
int i = 3;
double d = Convert.ToDouble(i);
uint ui = Convert.ToUInt32(i);
string s = Convert.ToString(i);
string s2 = "23.34";
double d2 = Convert.ToDouble(s);

Smaller storage sized data type converts to larger storage sized data types do not need casting. The numeric data types include sbyte, byte, short, ushort, int, uint, long, ulong, float, double, decimal.
byte b = 4;
float x = b; //ok
double y=b; //ok
int i=3;
double d=i; //ok

Casting is needed when converts a larger storage sized type to smaller storage sized data type.
int x = 220;
byte b = (byte) x;
double d = 34900;
int i = (int) d;

ToString method can be used to convert other data types to string.
int i = 3;
byte b = 4;
char c = 't';

Parse method can be used to convert string to other data types.
using System;
string str = "23";
int i = Int32.Parse(str); //i=23
double d = Double.Parse(str); //d=23

Byte array to string.
byte[] arr = { 85, 46, 98, 101, 95 };
string str = System.Text.Encoding.ASCII.GetString(arr); //str = U.be_

endmemo.com © 2024  | Terms of Use | Privacy | Home