Docsity

Type Conversion - C Sharp Programming - Lecture Slides, Slides of C Sharp Programming

Partial preview of the text

Download Type Conversion - C Sharp Programming - Lecture Slides and more Slides C Sharp Programming in PDF only on Docsity!

Type Conversion in C#

The Basics

 C# (and VB) are strongly typed languages

 That means you must explicitly convert data

from one type to another when using

assignment statements

 The data types on the left and right side of expressions much match

String Conversion (Example 1)

 The following will not work. Integers cannot

be implicitly converted to strings

int i = 3; string s; s = i;

 The following corrects the problem:

int i = 3; string s; s = i.ToString();

String Conversion (Example 2)

 Assuming that btnToStringDemo2 is a button

control instance, the following

txtOutput.Text = btnToStringDemo2.ToString();

 produces

System.Windows.Forms.Button, Text: ToString Demo 2

The Casting Problem

Creating a Cast

 To convert (cast) one data type to another,

you specify the data type (in parentheses)

before the variable reference

 Example

int i = int.MaxValue; int j = int.MaxValue; long l; l = (long)i + (long)j;

Creating a Multicast Event

Handler (1)

 Three radio buttons all fire the same event

this.radioButton1.CheckedChanged += new System.EventHandler(this.radioButtonX_CheckedChanged);

this.radioButton2.CheckedChanged += new System.EventHandler(this.radioButtonX_CheckedChanged);

this.radioButton3.CheckedChanged += new System.EventHandler(this.radioButtonX_CheckedChanged);

Creating a Multicast Event

Handler (2)

 Here we use a cast to convert the event

object to the proper data type

private void radioButtonX_CheckedChanged(object sender, EventArgs e) { RadioButton r;

r = (RadioButton)sender; txtOutput.Text = "radioButtonX_CheckedChanged fired. " + "The control " + r.Name + " fired the event."; }