Type Conversion

Views:
 
Category: Education
     
 

Presentation Description

how to do type conversion in C#.net

Comments

Presentation Transcript

Type Conversion: 

Type Conversion C# is statically-typed at compile time, so after a variable is declared, it cannot be used to store values of another type unless that type is convertible to the variable's type. However, we might sometimes need to copy a value into a variable or method parameter which is of another type. These kinds of operations are called type conversions .

Type Conversion: 

Type Conversion In C#, we can perform the following kinds of conversions: Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes. Explicit conversions (casts): Explicit conversions require a cast operator. The source and destination variables are compatible, but there is a risk of data loss because the type of the destination variable can be a smaller size than that of the source variable. Conversions with helper classes: To convert between non-compatible types we can use the System.BitConverter class, the System.Convert class, and the Parse methods of the built-in numeric types, such as Int32.Parse.

Implicit Conversions: 

Implicit Conversions For built-in numeric types, an implicit conversion can be made when the value to be stored can fit into the variable without being truncated or rounded off. For example, a variable of type long (8 byte integer) can store any value that an int (4 bytes on a 32-bit computer) can store.

Programming Example: 

Programming Example using System; class abc { public static void Main() { int a = 20056; long b = a; float c = 24567.45f; double d = c; Console.WriteLine("a={0}", a); Console.WriteLine("b={0}", b); Console.WriteLine("c={0}", c); Console.WriteLine("d={0}", d ); } } Output: a=20056 b=20056 c=24567.45 d=24567.4492175

Explicit Conversion: 

Explicit Conversion If a conversion has to be made even at the risk of losing information, the compiler requires that we perform an explicit conversion, which is called a cast . A cast is a way of explicitly informing the compiler that we intend to make the conversion and that we are aware that data loss might occur. To perform a cast,we should specify the type that we are casting to in parentheses in front of the value or variable to be converted. Explicit numeric conversion is used to convert any numeric type to any other numeric type, for which there is no implicit conversion, by using a cast expression..

Explicit Conversion: 

Explicit Conversion

Program Example: 

Program Example class Test { static void Main() { double x = 1234.78976d; double y = 4567.899d; sum s = new sum(); int q=s.add(x,y); System.Console.WriteLine("sum={0}",q); } } class sum { public int add(double a, double b) { int c = (int)(a + b); //explicit conversion return (c); } } //Output: Sum=5802

Parse Method: 

Parse Method Convert the string value to the specified data type equivalent. Int32.Parse Method :Converts the string representation of a number to its 32-bit signed integer equivalent. Boolean.Parse Method :Converts the specified string representation of a logical value to its Boolean equivalent. Char.Parse Method :Converts the value of the specified string to its equivalent Unicode character. Byte.Parse Method :Converts the string representation of a number to its Byte equivalent. Single.Parse Method :Converts the string representation of a number to its single-precision floating-point number equivalent. Double.Parse Method :Converts the string representation of a number to its double-precision floating-point number equivalent.

Program Example: 

Program Example /*to checked whether a number is even or not*/ using System; class even { public static void Main() { bool even; int num; Console.WriteLine("Enter a number:"); num = Int32.Parse(Console.ReadLine()); if (num % 2 == 0) even = Boolean.Parse("True"); else even = Boolean.Parse("False"); Console.WriteLine("The status whether the number ({0})is even is {1}",num, even); } } Output: Enter a number _45 The status whether the number (45) is even is False

String to numeric data type Conversion: 

String to numeric data type Conversion Numeric Type Method decimal ToDecimal(String) float ToSingle(String) double ToDouble(String) short ToInt16(String) long ToInt64(String) ushort ToUInt16(String) uint ToUInt32(String) ulong ToUInt64(String)

Program example: 

Program example using System; class abc { public static void Main() { int numVal = Convert.ToInt32("29"); numVal++; Console.WriteLine(numVal); } } Output:30

Methods : 

Methods A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method. The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started.

Method Parameters vs. Arguments : 

Method Parameters vs. Arguments The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method.

Program example: 

Program example using System; class abc { static int sqr(int x) { return (x * x); } public static void Main() { int a = 10; int s; s = sqr(a); Console.WriteLine(s); } }

Passing by value: 

Passing by value By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method.

Program example: 

Program example Using System; Class s1 { Int prod(int a,int b) { a=30; b=40; Return(a*b); } } Class s2 { Public static void Main() { Int a=10; Int b=20; s1 x=new s1(); int t=x.prod(a, b); Console.WriteLine("product of {0} and {1}={2}",a,b,t); } } Output: product of 10 and 20=1200

Passing by reference: 

Passing by reference R eference types are passed by reference. When an object of a reference type is passed to a method, the reference points to the original object, not a copy. Changes made through this reference will therefore be reflected in the calling method.

Program example: 

Program example using System; class s1 { public int prod(ref int a,ref int b) { a=30; b=40; return(a*b); } } class s2 { public static void Main() { int a=10; int b=20; int t; s1 x=new s1(); t=x.prod(ref a,ref b); Console.WriteLine("product of {0} and {1}={2}",a,b,t); } } Output : Product of 30 and 40=1200

Out keyword: 

Out keyword The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.

Program Example: 

Program Example class OutExample { static void Method( out int i) { i = 44; } static void Main() { int value ; Method( out value ); // value is now 44 } }

Params Keyword: 

Params Keyword The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

Program example: 

Program example /*A program to find the smallest number of a list*/ using System; class smallest { public int least(params int[] a) { int s = a[0]; for (int i = 0; i <=a.Length -1; i++) { if (a[i] < s) s = a[i]; } return (s); } }

PowerPoint Presentation: 

class array { public static void Main() { const int n = 10; smallest sm = new smallest(); int num; num = sm.least(23, 34, 67); Console.WriteLine("The Least number is:{0}", num); int[] b = new int[n]; for (int i = 0; i <= n - 1; i++) { Console.WriteLine("Enter a number:"); b[i] = Int32.Parse(Console.ReadLine()); } num = sm.least(b); Console.WriteLine("The Least number is:{0}", num); } } Program example contd..