Casting in C#

D

David P. Donahue

What is the C# equivelant of the following VB:

CType(controlTemplate, TextBox).Text = ""

I'm basically trying to use a more general object as an argument in one
of my functions and then change the behavior within the function based
on its type.



Regards,
David P. Donahue
(e-mail address removed)
 
N

Nicholas Paldino [.NET/C# MVP]

David,

You would do this:

// Cast to a textbox and set the text property.
((TextBox) controlTemplate).Text = string.Empty;

Hope this helps.
 
R

Richard Blewett [DevelopMentor]

The equivelent is the cast operator

((TextBox)controlTemplate).Text = "";

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

What is the C# equivelant of the following VB:

CType(controlTemplate, TextBox).Text = ""

I'm basically trying to use a more general object as an argument in one
of my functions and then change the behavior within the function based
on its type.
 
T

The Last Gunslinger

James said:
In addition to the short form given by the others, this method is a bit
safer:

TextBox tb = controlTemplate as TextBox;
if (tb != null)
tb.Text = "";

I agree,
Casting using "As" will return null if cast fails instead of an
invalidcastexception.

HTH
JB
 
J

Jon Skeet [C# MVP]

The Last Gunslinger said:
I agree,
Casting using "As" will return null if cast fails instead of an
invalidcastexception.

Why is that good though? If I've got something which *should* be a
TextBox, why is it good to mask the fact that my assumption is wrong?

There are times when it's better to use "as" - namely if your code
really doesn't know whether the cast should work or not - and there are
times when it's better to use a cast.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top