Blog Post

Converting Types in C#

,

I am not a great software developer. I’m OK, and I do know how to use Google and Stack Overflow well. Maybe my best skill is wording searches well? In any case, I’ve had to write a bit of C# lately to build an app for my Zero Downtime talk.

In no way am I an expert on this stuff, but I learned a few things while working on the client. One of these was how to get to/from various datatypes. Not a complex skill, but since I do it rarely, I decided to do a quick blog.

Creating Strings

I actually remembered how to take a number and convert it to a string. The ToString() method works on many  items. In my case, I used some variables as numerics, often a zero or one, but I wanted to display these in a textbox. To do that, I needed something like this:

txtRandom.Text = num.ToString();

Easy enough to write, but other items were more complex.

Strings to Int

I only had to go the reverse way a few times, but found there was no ToInt32() or similar. I was hoping for one, but a little google query helped me realize this is what I needed?

cmd.Parameters.Add("@year", SqlDbType.Int).Value = Convert.ToInt32(txtYear.Text);

In this case, I was adding an integer parameter from a value in a textbox, which was a strong. The Convert class has a ToInt32() method I used.

String to Date

In one demo I move to a date as a parameter, again getting a value from a string textbox. This was yet another method. In this case, there is a DateTime class with a Parse() method. I used it as such:

cmd.Parameters.Add("@start", SqlDbType.DateTime).Value = DateTime.Parse(txtStart.Text);

This worked great.

NULLs

One other item I needed was passing a NULL value to a proc. Part of zero downtime deployments involve staging your changes, and that sometimes means altering which parameters you use and sending in other values. In this case, I found a DBNull class with a value property. I passed null parameter values like this:

cmd.Parameters.Add("@year", SqlDbType.Int).Value = DBNull.Value;

More

There are obviously other conversions, but I’ll learn those as I need them. I know how to phrase a quick question and read through StackOverflow to find code I need and modify it. I’m good at asking questions and listening.

If you have advice, please leave me a comment. I had some fun doing this, and I’m glad I didn’t need to bother too many people to get this working.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating