Knowledge Management Banner

Knowledge Management Banner

C# Tutotial : Conversion and parse method : Part 4

Implicit conversion

  • When there is no loss of data and no exception thrown, than it is said to be as implicit conversion. It is done by compiler itself.
  • e.g. int i = 100;
  • float f = i;    <- done successfully

Explicit conversion
  • Conversion done by using cast method or by using class from .net framework, is called explicit conversion. explicit conversion also causes loss of data.
  • e.g. 1 
  • float val = 123.45f;
  • int i = (int)val;
  • e.g. 2
  • float val = 123.45f;
  • int i = Convert.ToInt32(val);

Parse method
  • It is the method available in datatype to convert the value into suitable form.
  • e.g. 1
  • string val = "32";
  • int num = int.Parse(val);
  • In above e.g. 1 in num variable we will get integer 32
  • e.g. 2
  • string val = "Hello World";
  • int num = int.Parse(val);
  • In above e.g. 2, an error will be thrown as "input string was not in correct format".
  • For using parse method the string should be always a number

Tryparse Method
  • It returns a boolean value depending on whether a string is converted or not.
  • e.g. 1
  • int val = 0;
  • string temp = "43";
  • bool result = int.TryParse(temp, out val);
  • In e.g.1 variable result will have true value and variable val will have the converted result as 43.
  • e.g. 2
  • int val = 0;
  • string temp = "Hello";
  • bool result = int.TryParse(temp, out val);
  • In e.g.1 variable result will have false value and variable val will have the default value that is assigned as 0;








No comments

Powered by Blogger.