Lab 1: Getting Started with Visual Studio

In this lab we will focus on:

  • Basic C# Fundamentals (compared to other languages)
  • Variables in C# (types available, naming conventions, etc.)
  • Quick and Dirty C# GUIs (using visual studio)

This lab will be due Sunday, Jan. 28th, midnight eastern time.

Basic C# Fundamentals

C# is a curly, compiled, statically-typed, semi-colon-using, object oriented programming language developed by Microsoft as part of their .NET family of languages. This means that C# shares a library of code with Visual Basic, another .NET language, so the two can easily be combined in larger projects.

C# is named after C++ (if you stick two +'s together you get a #, people who name languages are very funny people). However, C# is a heavily Object Oriented language like Java, and has more in common with Java than C++ because of that focus.

If you visit the online compiler Rextester, you'll notice that their default C# example is this:

//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            Console.WriteLine("Hello, world!");
        }
    }
}

The first four lines of this program (after the top comment) are using lines. These tell the compiler what packages from the library to load before we get started. I don't know why RexTester chose these four packages as the default: If you delete the second, third, and fourth packages from this list the "Hello World" program will still work just fine. That first line, using System;, is what allows us to use Console.WriteLine later.

Next, you'll see the namespace line and accompanying curly braces. The namespace block designates everything inside it as part of the same "package." Inside that, we have the public class named Program, which will hold our main method, public static void Main, which is where the program begins, like in most compiled languages.

For comparison, here is RexTester's default Java program, which you'll notice is almost identical:

//'main' method must be in a class 'Rextester'.
//Compiler version 1.8.0_111

import java.util.*;
import java.lang.*;

class Rextester
{  
    public static void main(String args[])
    {
        System.out.println("Hello, World!");
    }
}

To compile C#, you can use RexTester for only the most simple of programs (text output only, no keyboard input). We'll be using Visual Studio, which you can download for free here, since that is the preferred way to work with C#. If you do not have Visual Studio already, begin installing it now, since it takes a long time for most people. While you are installing Visual Studio, be sure to select the "NET Core cross-platform development" workload option, as this will allow you to program in C#.

Variables in C

C# has similar variable types to Java, Visual Basic, and C++. The common types you'll see are:

int myWholeNumber = 123;
double myRealNumber = -1.23;
string myCatsName = "Spencer Reid";
bool myTrueFalseValue = false;

C# also uses the common math operators:

int answer = X + Y - Z*3;
double volume = 4/3 * Math.PI * radius*radius*radius;

// every year on your birthday run this line of code
age += 1;

// this would also be nice
salary *= 2;

Like some languages, but not all (like Python), C# lets you concatenate non-string values with string values:

int score = 100;
string name = "Jane Doe";
Console.WriteLine("Great work " + name +
                  ", you scored a " + score +
                  "on the exam!");

This means that C# has the "string trick" from JavaScript where you can easily turn any value into a string:

string myString = "" + anyVariableIWant;

To convert between other types, though, C# has a handy Convert tool:

int myWholeNumber = Convert.ToInt32(myString);
double myRealNumber = Convert.ToDouble(myString);
bool myBoolean = Convert.ToBoolean(myString);

Finally, C# uses the standard rules for naming variables, with a few conventions:

  • variable names must start with a letter or underscore
  • variable names can contain (but not start with) numbers
  • variable names can never contain spaces or other punctuation
  • variables should be named with CamelCasing or under_scores to aid in readability
  • namespace, class, and method names start use UpperCamelCase by convention
  • constants (like Math.PI) use ALL_CAPS_WITH_UNDERSCORES.
  • single letter variable names can be upper or lower case, but never use a lowercase L as a variable name or an O, whether upper or lower, because these look too much like 1 and 0.

Quick and Dirty C# GUIs

(If you are having trouble with Visual Studio or getting it installed, shoot me an email describing the problem, what you have tried, and screenshots. Then, while you wait for a reply, continue to try to resolve the problem on your own.)

Once Visual Studio is installed and working, follow along with this video: Creating Your First WPF Application.

Although the video is for a previous version of Visual Studio, the steps should be approximately the same:

  1. File > New > Project > C# > WPF Application
  2. Give the project a meaningful name at the bottom of the prompt before hitting Ok
  3. Open the Toolbox (on the left by default) and drag/drop a GUI component onto the canvas
  4. Make finer edits to the XAML code if need be
  5. Run the program with Ctrl+F5

Doing this, you should be able to create the interface for a program. This means that you can have textboxes, buttons, pictures, and so on, but nothing will happen when the user interacts (clicks, etc.) with your program.

This is perfectly alright, it turns out, since C# was written to make creating interfaces and creating "business logic" two separate processes. The benefits to this are:

  • GUI bugs and business logic bugs will be less "coupled" together, making debugging easier
  • non-functional GUIs can be made quickly to help plan and show prototypes to, for example, a client or your boss, which helps get feedback early on in the software development process. (no need to code the logic for a button if the client doesn't want the button there in the first place, right?)
  • logic and code and other program pieces can be better packaged and reused, following approaches such as "MVC," which split the Model (the data), the View (the GUI), and the Controller (the business logic).

We'll start with GUIs because:

  • It's the order of the chapters in the book
  • It's more prone to installation/etc. errors, so we'll try to get those out of the way now, then come back in more detail once we've covered the language
  • Students like seeing the results of their programs, and this has been shown to help learning a language, so even if the program doesn't do anything yet, it's easier to see how it might do something later.

Grading and Submission Instructions

To submit, write your responses to the following questions in a Word document, then upload it to Blackboard under this week's folder in Current Assignments.

Labs are due two weeks from when they are assigned, on Sunday at 11:59pm eastern time.

Labs are each worth 5% of your final grade. Scoring on your submission will be based on the following rubric:

0% - Student does not submit on time or submits plagiarized or unacceptable work. Double check that you have attached the right file, as usually students get zeros because they upload a previous week's Lab by accident.

1% - Student answers less than half of the questions with sufficient or accurate responses. Make sure that you are leaving yourself enough time to complete the Lab each week, as usually students submit incomplete work because they were rushed at the last minute.

3% - Student answers almost all questions with sufficient and accurate responses. If you encounter a problem or have a question about one of the questions, be sure to post in Ask the Instructor well before 24 hours before the due date, then continue to attempt to resolve the issue on your own while you wait for a reply.

5% - Great job, maximum points! The student answers all questions accurately and sufficiently, demonstrating the best of their ability.

Note, because Labs span two weeks' worth of reading, it is recommended to go through the Lab twice, once after the first reading where you answer everything that you can, then again after the second reading where you answer everything else.

Part 1

  1. A program that translates high-level programs written in C# into machine code is called a ________.
  2. A series of characters that appears within double quotes is called a ______ literal.
  3. The C# method that prints a line of text is (a) Console.WriteLine, (b) Console.PrintLine, (c) Console.DisplayLine, or (d) Console.PutsLine.
  4. Which of the following is not a legal variable name in C#? (a) per cent increase, (b) annualReview, (c) HTML, (d) alternativetaxcredit
  5. A comment written /* like this */ is a (a) line comment or (b) block comment?
  6. What does the % math operator do? For example, 4 % 2 is equal to 0.
  7. True or false, the / math operator, when used on integers, always rounds down.
  8. The only two values a boolean variable can hold are ____ and _____.
  9. What does WPF stand for?
  10. In Visual Studio, when making a WPF application, you drag/drop components from the _______.

Part 2

  1. Which of the following is the best example of a class and an object within that class, in that order: (a) robin and bird, (b) chair and desk, (c) school and KCTCS, or (d) oak and tree?
  2. What is the value of 22 / 7 in C#? (Hint: are we using integers or doubles in this equation?)
  3. What is the value of 22.0 / 7.0 in C#?
  4. What is the value of 17 / 2 + 14 / 2 in C#?
  5. What variable type is the most appropriate for representing each of the following values: (a) your age, (b) your bank account balance, (c) your shoe size, and (d) your middle name?

Part 3

  1. The following variable names are all incorrect according to the rules of C#: (a) last name, (b) phone#, (c) 123DruryLane, and (d) air-plane. Explain what is wrong with each variable name and propose a new, correct name for each.
  2. Create a "quick and dirty" WPF application in Visual Studio that looks like a gas pump. That is, drag/drop text boxes, buttons, etc. onto the canvas in Visual Studio and size and place them so that your interface resembles that of a typical gas pump. Embed a screenshot of your program running as your answer to this question.
  3. Describe the steps you took in creating the above program, including which buttons you had to click as well as how to went about deciding which WPF components to use, where to put them, how to size them, and so on so that your program would look like a gas pump.
  4. In your opinion, what makes a good interface? Explain.