Documente online.
Username / Parola inexistente
  Zona de administrare documente. Fisierele tale  
Am uitat parola x Creaza cont nou
  Home Exploreaza
upload
Upload






























Working with Variables, Expressions, Statements and Operators in C#

computers


Lesson 4

Working with Variables, Expressions, Statements and Operators in C#



Hello again. In this lesson we will talk about using variables in C#, what they are, how to declare them, and I will explain what data types are and how they fit into the picture, how to convert values from one data type into another, and so on. And then we're going to talk about the difference between statements and expressions, and look at the different types of each. So let's get started right now.

We will start by talking about the one of the building blocks of code- variables. If you remember back to high school algebra, you might remember a problem that looked a little bit like this:

x=3, y=x+7, so what is y?

Now in this problem we can see that there are two variables: x and y. Since x is assigned to the value 3, we can easily see that y would then have to equal 10. And at their essence these variables simply represent some value, We can think of them as buckets that contain a value or that represent a value. In computer terms, a variable is spot or a space that's allocated in the computer's memory to store some value. And we as programmers can reference the value that is in the computer's memory by using the name of the variable that we give it. Also back in algebra, we only worked with numerical values, but variables in the programming world can contain strings, dates, big numbers, small numbers and much more. In order to know how big or small to make that bucket in the computer's memory, we have to declare the variable in order to tell the computer what size of information we expect to store in there.

So let's get started with this lesson by going and creating a new project so we can write some sample code. We will call this project Lesson04 and we'll select "OK."

And what we'll do, just for fun, we will put a single button on the form, double-click it so we can get to the code view, and we will spend the majority of our time here.

Declaring a variable is pretty straight forward. All you need to do is first of all, to find what data type that we'll use, in this case we will use the data type of string. We will talk about data types in just a moment. And then give the variable a name; in this case we will call this "myStringVariable," and we can name it anything that we want to name it as long as it doesn't conflict with the exact spelling of an existing variable or some object within the .NET framework or something along those lines. You don't have to remember what those are because Visual C# 2005 Express Edition will tell you if you've used a name that is already in use by some other object or in use by Visual C# or the .NET framework. So don't worry about that for now.

We can also create another version of a variable and that is called the "initialized" variable. You are basically taking two steps in one line of code. So in this ca 11511q1624l se, everything starts off the same, but then we're also going to assign it some value right away. In this case, I have just assigned this to an empty string but we could assign this to "Bob" or some other string that we wanted to put in here by default. So basically in that second line of code we're defining how big the bucket should be by saying it should be a string, and then immediately filling up the bucket with some value. Let me type a couple more lines of code.

So in the first two lines of code, we created two variables. Each of their types are strings. Strings can contain alphanumeric characters, both numbers and letters, and any other key combination on your keyboard. However, if we need variables that can be used for mathematical equations, or to use for counting or something where there might be some calculation going on, then we would need to use one or several different numeric data types - either the Integer or the Double, or a special case called the Boolean.

The first numeric data type that we used in our example was an Integer, or rather Int as we typed it out. And the Integer data type will allow us to create variables that can store values between a negative two billion and a positive two billion. The next data type that we used was a Double, which as you can see from the graphic allows you to create fairly large negative numbers to fairly large positive numbers. Also, it allows you to put up to 15 digits after the decimal point. The practical difference between the Integer and the Double is that the Integer allows you to keep whole numbers and is used frequently within properties and settings and things of that nature, and the double allows you store data that also has decimal places. Finally, we have demonstrated the use of the bool, the Boolean, and that allows you to keep values that are either true or false. So we're often using those in Expressions, and we will talk about Expressions near the end of this lesson. Now there are a bunch of other data types that are available, but these four will help you get a long way as you are starting out. For those of you who are going to be Computer Science majors you may need to know all, I think it is twelve or so, numeric data types that are available. But for those of us who are just average everyday programmers,

who just need to create applications that are usable, typically these four, and there are maybe two or three others that we might need to focus on, will get us just about everywhere we need to go.

Now the one thing that we haven't talked about yet is that C# is a case-sensitive language meaning that we can possibly do this - and even though these two variables are spelled exactly the same, by virtue of the fact that we use a capital V in value in the second variable declaration, means that these are two different variables. So this can be pretty tricky, it can be a "got you" and you should be very cognizant of what you are typing out. You need to be consistent and cautious whenever you are declaring and using variables that you create. Now the good news is that the code view will try to help you out as much as possible by correcting any capitalization mistakes that it can, but the bad news is that there might be situations where you are on your own, just like this situation where you declare two variables with very similar names. So the best advice is that always be aware of what you are typing and why you are typing it.



Let's take a moment to talk about strings since we glossed over them just a moment ago. Whenever we type in a string, like we did in the HelloWorld application, you remember we typed in the word "HelloWorld" in the Message Box and we put quotation marks around them. Why did we use the quotation marks, why do we do that? Well, it is really simple. It helps the C# compiler to distinguish between a string literal versus a variable name. We have already been talking about variable names so the question is, that what is a string literal? It is basically any fixed set of numbers and letters that are arranged together, that need to be displayed somehow. So here is one way to make the distinction - the variable is the bucket and the string literal is what can go into the bucket.

A string literal can be a message that we want to display to the user like we did in the HelloWorld application, it can be values that we want to save into a file or a database, it could contain the file location that we want to save into, or it could be any other text that has some meaning within our application, whether to the user, or to the saved off, or whatever the case might be.

So just for fun let's consider this short example to make the distinction between the two. I'm going to create a variable called "Hello," and then I'm going to sign our variable - our bucket called Hello equal to literal string Hello. Then we will do this. Let's go and comment out some of these lines of code here so we can just get rid of them. I'm going to use my multi-line comment to do that, we learned about that in the previous lesson. I'm going to run the application. Now what do you suppose will happen here? We will show two message boxes and each one should say the word "Hello." There is the first one and there is the second one. Now what did we really accomplish here? That is a good question. The difference between these two message boxes is that the first message box uses a variable, and it will check in our computer's memory to see what is in the "Hello" bucket. It happens to be the word Hello. The second message box shows a string literal called Hello.

So if we were to change the first Hello to store the value HelloWorld, we would get a much different response. HelloWorld and Hello. So hopefully that helps to make the distinction between a string literal like all the text that is in red here. HelloWorld and Hello in the message box, versus name of a variable which is this first Hello. So you might be wondering yourself, why do we use variables? Simply put, it is so that we can save values off until we're ready to use them, or refer to them, or compare them, or evaluate them, and there might be a dozen other reasons. At this point, a simple example might help make a little bit more sense. First of all let's comment out this little example. Now the next thing I'm going to do is go back to my designer, and I'm going to add two textboxes on my form. And here what I'm going to do is declare two variables. And then what I'm also going to do is to come back here, and let's put a label, and let's stretch this out. Well I think it is auto stretch, so we will be fine there.

So now let's give this a try. Notice what happened. Whenever I click the button event, it grabbed off the value from the first textbox and the second textbox and concatenated them together, along with an empty space, which gave me the ability to put "Bob" and "Tabor" together onto the same label.

Now this is still a fairly simple example. But we're able to store off values from our textboxes, and then refer to them at some point in the future in order to display them back to the end user or maybe we save it to a database or a file, whatever the case might be. It is also available to us for processing, for making changes to it and so on. So that is a pretty simple example so let's move on.

To paraphrase what we said earlier in this lesson, whenever you declare a variable, you are creating a space in memory that can hold the value of a certain data type. But, what if you try to put a value into that variable, that is the wrong data type, what is going to happen? For example what if I were to do this - Let's comment out the rest of this. Notice whenever we try to run the application, Visual C# 2005 gives us an error. It says, "Would you like to continue and run from the last successful build?

We're going to select the "no" button because we don't want to run from the previous build. We want to run from the code base that we're currently working on. And the error list pops open, and notice that it gives us a description of the problems within our code. It found one error, and it says it cannot implicitly convert type string to integer. So we had a problem trying to convert the word "Bob" into a numeric value. Let's try the opposite, let's do this. String equals 3; Once again we get a problem - cannot implicitly convert type int to string. Let's try another experiment as well. Let's go back to making this an integer, and then let's create a double, and let's see if that works. Okay it compiles, we didn't really ask us to show any output, but there were no problems whenever we ran the application. Now let's try the other possibility, and change this around where we try to put 3.14 into our integer. It should not accept it, but let's see what happens. Notice we get an exception. So the answer to our original question is not so easy.



In some cases, the value will be implicitly converted to the correct data type, which simply means that the C# compiler will perform the conversion for you so you don't even have to think about it. That was the case previous to this one, where we had int my value equals 3, double my other value, and then we set my other value equal to integer. Since the number 3 could be converted implicitly into a double value without any problem, C# was able to take care of that for us. But in this case we have a double and we trying to put that double value 3.14 into an integer, C# croaked and said we can't do this, there is a problem. Let me show you another example. We'll use our textboxes again that are on our form.

Alright, first of all, do you think this is going to work in the way we have typed in right now? Let's go ahead and run it and see what happens. Oh, we got several problems. Let's take a look at what the problems are - they all have to do with implicitly converting. The first two have a problem implicitly converting string, which is what is stored in the text property of a textbox, into an integer, which is what we declared the variable first textbox as. The same can be true of the second line of code that we have here. The last line of code with the blue squiggly line underneath it tells that we can't implicitly convert an integer, which is the data type of our variable result, into a string, which again is what we would want to put into our label control's text property. So how do we rectify that? Well, we have to do some data conversion in order to make this happen. I will explain what I'm doing in just a moment.

OK what I have done just now is called explicit conversion, which means that you have to write the code to perform the data conversion. The C# compiler will not perform the conversion for you, and will not allow you to compile and run the application until you write code just like this. Now, this is where things get tricky because this might not make a lot of sense at this moment. So just take what I'm about to say at face value, and later on in your learning you will understand the "why," instead of what I'm about to show you which is the "how." If you want to convert a string value into a numeric value, you simply enclose the string variable or the string literal with one of the following: either like I have done here int.Parse and then use parentheses around it. That will take whatever the string is and parse that string and try to make it into an integer value explicitly performing the conversion that you have requested.

Now if it can't perform the conversion, say for example somebody typed in the word "Bob" in the textbox then you have a runtime exception, and we will talk about exceptions much later in this series of lessons. Now the second example, the one at the bottom - the result.tostring, this will take some numeric value, whether it is an integer, double or a Boolean, and it will attempt to convert that value into a string. Now that should probably be more successful because this string's a little bit more liberal about what values can be inside of it. So this probably won't throw an exception no matter whatever you throw at it for the most part. Now let me just say this, we used integer.Parse, or int.Parse, we can also use double.Parse or bool.Parse depending on what type we want to accomplish. Let's run our application and we will use this as a simple calculator, where we will add 3 plus 6 and we will display the value. You can see it displays it as 9 in our label.

No if you would like to know more about how this works, the "why" behind what is going on here, you will need to understand the difference between static and instant references to objects. It is a little more advanced. I didn't want to get into that. We will begin to cover objects and references in lesson six. So just hang in there and perhaps this is going to make a little more sense as to why I used the .Parse method or the .tostring method in order to perform a conversion. At this point I just recommend that you keep in mind that in order to perform a conversion, that you are going to need to use one of these methods just like I did right here. Just for fun, let's go ahead and break our application like we said we would a moment ago, and here I will type "Bob" and here I will type the number 6.

So what we're trying to do is 6 + Bob and what we wind up getting is a big problem. The nice thing about Visual C# 2005 Express Edition is that it will attempt to explain the exact nature of the problem. It will say that "The Input String was not in the correct format." It expected to find a value in the textbox that could be easily converted into an integer value. Because we used int.parse, we would expect to see that value in there before we assign it into our integer data typed variable called first textbox. So we can read through the troubleshooting tips that we have here, we can look at the detail of the problem. Or we can copy the exception detail to the clipboard if we want to post it on a forum or a request for help from a friend or on a forms or whatever the case might be. So we're going to close this down and stop the execution of the application. I just wanted to show you what that would look like. So at this point, we have written a very fragile application. Obviously we would need to do a little more checking, a little more validation before we attempted to do this data conversion of what is in the textbox into a more restrictive data type that only accepts numeric values.

Let's finish up this lesson with some terminology that we're going to need for the next lesson. Let me comment out some code here. OK, here we go. Let's do this. OK now let's run our application and see if this works. And we get our problem trying to compile the application. Let's see what the problem is. In the error list we get the message that only an assignment, call, increment, decrement, and new object expressions can be used as a statement. So what does this mean? Why do we get this error whenever we try to compile this application?

Well, the reason is because "x+3" is not a statement but rather it is an expression. In other words it is only half of what the C# needs in order to execute this line of code. Put another way, it doesn't really do anything. As we saw from the error in our error list, a valid statement can consist of some sort of assignment like x=3, or a call like MessageBox.Show("Hello World"), which we used in our first example.



It can be an increment or a decrement of the variable, like x++ or - -x.

Or it can be a New Object Expression which we will talk about in lesson six. Let's hold off on that one for a while. But as you can see here, we haven't done any of those, all we have done is just try to use x+3 but we didn't assign x+3 to anything. We didn't make a call to anything. We didn't increment or decrement anything in the manner which C# would have us do it. Although I guess we're implying here that we want to increment x by 3 but that is not the way we would do it. If we wanted to write that we might do something more similar to this - but we didn't do that, that would be an assignment. We have this line of code.

So as a rule of thumb, expressions can be evaluated. We can evaluate an expression and figure out what the value would be, but it is not a statement. Statements can be executed. So let's talk about expressions a little bit more. An expression can be evaluated. What does that really mean? Well, an evaluation is what you do with math problems. You evaluate the answer by either adding, subtracting, multiplying, dividing, or operating the value in some way, in order to determine the answer to the problem.

Once you get the answer usually you will have to write it on your paper or you have to raise your hand and tell the answer. Well, in this case we're merely evaluating, but we don't write it down, we don't do anything with it. It is just out there by itself.

Now here is a good example. We didn't really go through it in very much depth earlier. Let's go back to this one over here, specifically that last line.

Label1.text=first Textbox+" "+second Textbox

Before label1.text could be changed to the word "Bob Tabor," the C# compiler had to take the value from the first box, add it with a space, and then add it to whatever value is stored in the second textbox value, which would have been "Tabor." And once that whole evaluation took place, only then could it be assigned to the text property of our label. So this entire line is considered a statement because we evaluate it, and then we took the evaluation and assigned it to a property. If we were to just do this however, on another line of code, that would only be an expression. And it could not be used as a statement within C# so let's go and delete this and comment all this out.

Now I wanted to make this point about evaluating expressions because it is something that we will be using quite a bit in the next lesson on branching and iteration statements. In those cases we're going to be doing a different sort of evaluation, we're going to be evaluating to see whether an expression evaluates to be true or false.

So just as a quick warm-up to the next lesson, let's go through a few examples. First of all,

Is 3 < 2? True or false?

Well, that is obviously false. 3 is not less than 2. Let's switch it around.

Is 3 > 2? True or false?

Well, that statement, that expression rather, is true. Okay, let's go on to the next one.

Given that int x=3, x=3; True or false?

Well, that is true. Now let me explain some of the operators that are being used here. A single "=" sign is used for assignment. A "= =" sign is used for evaluation. Another way to think about it is that a "=" sign is used for telling. I'm telling x to store the value 3. A "= =" sign is used for asking. I'm asking whether or not the value of x equals 3. So just keep in mind that in C#, unlike other programming languages, there are different operators used for assignment and evaluation. Okay, one last one,

Given that x=4, is x != 3? True or false?

Well, that would obviously be true, and just to explain the operator that is used here, the exclamation point (!) combined with the equal (=) sign evaluates to "not equals". So in that case, the answer is true. 4 is not equal to 3.

So we learned about a couple of new operators that we can use to evaluate an expression, and now you are ready to move on to the next lesson and apply some of this new-found knowledge to branch iteration statements.

If you enjoyed watching this video, please visit www.learnvisualstudio.net to download and watch over 500 videos just like this one aimed at all skill levels on many different topics related to C#, Visual Basic.NET, ASP.NET and more. Thank you.

[29:55]





Document Info


Accesari: 1578
Apreciat: hand-up

Comenteaza documentul:

Nu esti inregistrat
Trebuie sa fii utilizator inregistrat pentru a putea comenta


Creaza cont nou

A fost util?

Daca documentul a fost util si crezi ca merita
sa adaugi un link catre el la tine in site


in pagina web a site-ului tau.




eCoduri.com - coduri postale, contabile, CAEN sau bancare

Politica de confidentialitate | Termenii si conditii de utilizare




Copyright © Contact (SCRIGROUP Int. 2024 )