Later Today: ASP.NET Tutorial 2: Introduction to C#

ASP.NET Tutorial 2: Introduction to C# (Structure)

Visual Studio creates your code-behind class for you every time you create a new aspx page, so you really don’t need to worry about it right now. Just understand that classes need to be defined the same way that methods and variables are (with different keywords having different effects on them).
In this example, TextBox1 is the id value of an <asp:TextBox> object on the aspx page. The .text after it tells C# that we want to change the value of that object’s text attribute. This is one of the basics of object-oriented programming.
Web controls are objects that you place on your aspx page. There are web controls for most common form elements, like text-boxes, drop-down lists, etc. The advantage to using .NET web controls instead of typical HTML form elements is that you can access them directly from your code-behind classes as if they were just another object (like a class).

For instance, let’s say we have a textbox with an id of “tbFirstName” and we want it to automatically load with my first name (“Matt”). From our code-behind class, we can simply call the object by it’s id, access it’s “text” property using the period, then set it’s value as if it were a variable. Like this…

tbFirstName.text = “Matt”;

And now when that textbox loads, it will automatically have the text “Matt” inside it.

Prerequisites: General familiarity with Visual Studio or Visual Web Developer. Familiarity with core web design principals and technologies (X/HTML, CSS).

This tutorial is meant to give you a general understanding of C# structure and object-oriented programming, including the oft-neglected hows and the whys. Topics covered will include an overview of variables, methods, classes, and namespaces.

Hopefully, by the end of this tutorial, you’ll have a general understanding of how C# code is structured and organized.

Note: Conditionals (if/else statements, switch statements, etc) will be discussed in next week’s article.

> Setup

This section discusses the creation of a new Visual Studio project so that you can follow along.

If you would like to follow along with this tutorial on your own computer, you should create a new Web Site in Visual Studio and call it “DotNetBasics”. We’ll use this web site in future tutorials as well.

Creating a New Website

To create a new website, go to your File menu, and select New Web Site… (be careful that you select the correct option. Clicking on New Project… creates a Windows Application project, not a new web project).

You should then see a window like the one below. This screen lets you set some information about your new project – like the type of project, the programming language to use, and where the project should be saved.

Visual Studio 2010 Ultimate - New Web Site

On this screen, you want to make sure that you have “ASP.NET Web Site” selected, as well as “Visual C#” for the language. VWD allows you to create your websites in either Visual Basic or Visual C# – this site will only cover C#.

The nice thing about C# is how similar it is to other major programing languages – like PHP, JavaScript, or Java. If you learn one, the others are that much easier to pick up. Before you continue, you should also rename your project folder (under “Location” at the bottom of the Window). By default, VWD will call it WebSite1 – you can either leave the generic name or rename it to something more meaningful like DotNetBasics (note on project location). When you’re happy with your project settings, click OK.

VWD will automatically put together a very basic website for you. If you’re using VS2010, it will look like this (or click here to see it in Visual Web Developer 2008 Express):

Visual Studio 2010 Ultimate - An Open Project

Visual Studio 2010 Ultimate - An Open Project

> Statements, Blocks, Keywords

Discusses statements and blocks, C#’s most basic organizational concepts.

> Variables

This section discusses variables, one of the most basic components of any programing language.

Description

Variables are the most basic building block in C#. A variable is like a container, which you give a meaningful name to – and each container is used to temporarily store data. The container is called a variable, and the data you store inside the variable is called a value.

Simple, right?

All variables are not the same however – each variable can only be used to store one type of data. For instance, you would create a variable that only stores numbers – or a variable that only stores plain text – or a variable that only stores dates. These are, not surprisingly, called DataTypes.

To create (or “declare”) a new variable, you simply specify a DataType, give the variable a name (it must be unique and cannot be a C# keyword), then put an equal sign followed by a value (of the correct DataType). The formula for creating a new variable is this:

[DataType] [UniqueName] = [Value];

The example below shows how to create a new variable (which we’ll call iMyNumber) that can store only whole numbers (integers) and assign it a value of 3.

C#:
int iMyNumber = 3;

In english, this example would read “Create new integer variable, named iMyNumber, and set it’s value to, 3.”

DataTypes

At this point, you should pretty much understand the point of DataTypes. By specifying the exact DataType, you can easily perform certain operations on them – like using multiple integers to perform a mathematical calculation, or assembling multiple strings (plain text) into a sentence. Below are some of the core DataTypes you should familiarize yourself with:

Keyword Type Example Description
int integer 3 A positive or negative whole number (this is limited to about +/- 2 billion – setting a value to large or small will cause an error).
string string "Bob Marley" Usually used for plain text, strings must be wrapped in quotes.
bool boolean true Used like a light switch, booleans must always be either true or false.
decimal decimal 1.5m Stores decimal numbers (unlike integers). Usually used for money, the number must end with the letter ‘m’ to avoid accidentally assigning the value to the wrong type.
datetime datetime 12/25/2010 12:00:00 AM Stores dates and/or times.

There are other DataTypes, of course, but these are the ones I want you to concentrate on for now. I’m sure things are complicated enough without forcing unnecessary information down your throat.

Review

In review, in order to create a new variable, you simply follow this formula, replacing the descriptions and brackets with whatever you need:

[DataType] [NewVariableName] = [Value];

If you want to give an existing variable a new value, do not state it’s datatype again – merely specify the name of the variable you want to change and assign it a new value. Refer to this formula:

[ExistingVariableName] = [Value];

Tip 1: It’s a good practice to begin your variable names with an abbreviation of their datatype – just so you remember what you’re working with. An integer for tracking a person’s age might be called iAge, while a string that stores a person’s name might be called strName, or DateTime that stores an anniversary date might be called dtAnniversary. You don’t have to do this, of course, but you’ll be a happier, less confused programmer if you do.

Tip 2: Variables, like everything else in C#, are cASe-SeNsiTive. So if you create a variable called iMyhouse, then trying to access it by typing iMyHouse will not work (fortunately, Visual Studio will tell you when a variable doesn’t exist, so you shouldn’t have too much a problem keeping this straight).

Tip 3: Try to keep variables alphabetical only. While you are technically allowed to use numbers in variable names (provided a number isn’t the first character), it can make your code harder to read. Variable names also cannot contain white space. Try to keep variable names short and descriptive.

> Methods

This section discusses Methods, the building blocks of any C# project.

Methods are a lot like machines. They let you group together bits of code so that you can easily reuse them over and over (or just keep your code organized). For instance, let’s say you write some really neat code that you want to use somewhere else. Instead of rewriting that code, you simply put it into a method – then you can call the method by name every time you want to run the code that you’ve put inside it. In other words, methods make your code reusable.

Creating Methods

The most basic method possible is structured according to this formula:

[ReturnDataType] [NewMethodName]([Parameters]){ [CodeToRun] }

For example purposes, let’s take a real-world machine and imagine it as a method. We’ll call this hypothetical method CoffeeMaker(). In the real world, a coffee maker works like this: Water and beans are put in, the water and beans are combined, coffee comes out. Here’s how this looks when turned into a method:

C#:
string CoffeeMaker(string strWater, string strBeans)
{
   string strCoffee = strWater+strBeans;
   return strCoffee;
}

Using Methods

The above method needs to be given two values in order to function and both values must be strings. Did you notice how we’ve declared two variables within the parentheses? These are called parameters. When we call up the CoffeeMaker() method to use it, we can use any two strings as parameters (separated by a comma), and the method will automatically use the strings we give it as values for those variables.

The following example shows how we might use our CoffeeMaker() method…

C#:
string strCoffeePot = CoffeeMaker("water","beans");

This is what is happening in the above example: We pass two strings into CoffeeMaker() (because when we created the method, we specified two parameters). CoffeeMaker() then combines both strings and returns the value ( which is “waterbeans” ). By setting the variable strCoffeePot equal to CoffeeMaker(), the strCoffeePot variable will use the value that CoffeeMaker() returns.

In other words, the variable strCoffeePot is given a value of “waterbeans”.

Return Values

Methods do not necessarily need to return a value (it’s optional). This is useful if, for instance, you need a method that simply writes some data to a database – or a method that directly modifies content on an aspx page. In either case, you simply create the method using void as the return DataType.

Note: When a method has void as it’s return value, you should not use the return keyword inside that method. This is what a method with no return type looks like:

C#:
void UpdateTextBox()
{
    TextBox1.Text = "This is new text";
}

Don’t worry about what TextBox1.Text means – we’ll cover it later. If you’re really curious, though, click here.

> Classes

This section discusses Classes, a tool generally used to organize Methods.

If methods can be thought of as machines, a class can be thought of as a factory. Generally, a class is used to group together multiple methods that serve a similar purpose. For instance, a teddy bear factory might contain a lot of different machines – machines for stitching, machines for stuffing, machines for painting – but ultimately, all the machines in the factory are used for making teddy bears.

Using a practical example, let’s say want to create a class specifically dedicated to validating form data. Inside that class you might have one method that checks email addresses, another that checks phone numbers, and another that ensures that a required field has data. They all do slightly different things, but they all serve the same general purpose of checking the data in a form.

Ultimately, how you organize your code is completely up to you as a programmer – but when you build classes, you should try to keep them as logical as possible.

Code-behind Classes

In ASP.NET, dynamic web pages you create do not end in .html, but .aspx. Every aspx page consists of two files – the aspx page itself (which contains the html and visual stuff) and a class file (which contains the code and functionality).

A code-behind class is a class that Visual Studio automatically creates whenever you create a new aspx page. These classes are page-specific, and generally only affect the page they were created with.

To see an aspx page’s code-behind class, simply click the little [+] icon beside the page in the Solution explorer (if you created a new project earlier, try Default.aspx). This will reveal a file that has the same filename is the aspx page, but ends in .cs (for instance, Default.aspx.cs). Double-clicking this cs file will open the class in the editor panel.

At the top of the class page you will see something similar to this…

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

These are framework references. We’ll cover these in more detail in the Framework section… but they are essentially shortcuts to .NET namespaces. By adding these references to the top of a class file, you can access the classes and methods contained in those namespaces without having to write out the entire path every time you want to use one (and some of those paths can get very long).

Beneath the framework references you will see something like this…

C#:
public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

The class itself is defined by the line public partial class Default : System.Web.UI.Page. We’ll discuss what all that stuff in the class declaration means in a later article… but in the mean time, just remember that it’s a complicated way of creating a class.

Going back to our last example, notice how the class starts out with one method, called Page_Load(). This is the single most important part of any code-behind class. Every time an aspx page is requested from the server, the Page_Load() method will execute automatically.

What makes this useful is that the finished HTML isn’t sent to the browser until after the Page_Load() method has finished. Essentially, the server runs the Page_Load() method, compiles the aspx page into proper html (often by using code in the code-behind class), then sends that finished html to the browser. A lot of the code we’ll be writing in future tutorials will start in the Page_Load() method.

Tip: No matter what, Page_Load() will always execute before anything else. This is important because the other common way of executing code is by using buttons – but methods attached to buttons STILL don’t execute until after Page_Load() is finished.

When you create your own methods, you should always place them within the class block, after the Page_Load() method (never place methods inside other methods – methods should only ever be placed directly within a class). Like this…

C#:
public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
	  string strMyCoffee = CoffeeMaker("water","beans");
	  //strMyCoffee now has a value of "waterbeans"

	  string strMyLatte = CoffeeMaker("milk",strMyCoffee);
	  //strMyLatte now has a value of "milkwaterbeans"
    }
    string CoffeeMaker(string strWater, string strBeans)
    {
       string strCoffee = strWater+strBeans;
       return strCoffee;
    }
}

Standalone Classes

What if you want to write a method that you can use in multiple pages? Since you know that code-behind classes can only be used on a single page, does this mean that you have to copy a method into every page’s code-behind class that you need it in?

No! You can create custom class files that you can then use anywhere in your project.

To add a custom class to your project:

  1. Right-click on your project in the Solution Explorer (it’s the one with the globe icon at the very top of the list)
  2. Select “Add New Item…” from the popup menu
  3. Select “Class” from the list of available items.
  4. Give the class file a meaningful name, then click Ok.
  5. If Visual Studio asks you to put the file in the App_Code folder, say yes (custom classes should always be placed in the App_Code folder).

If you open this new class file, you’ll see that it’s not as complicated as an aspx page’s code-behind class. The example below shows a new, empty class named Class1 (this example is 100% generated by Visual Studio when you create a new class file).

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

///

/// Summary description for Class1
/// 

public class Class1
{
	public Class1()
	{
		//
		// TODO: Add constructor logic here
		//
	}
}

You may have noticed that instead of a Page_Load() method, you have a method that has the same name as the Class. This is called a constructor method. We’ll cover constructors more in a later article – but for the time being, you can simply leave it empty (don’t delete it – at least one constructor is required).

To create a method that can be used anywhere in your project, simply create it within the class and add the public static keywords in front of each method declaration. Like this…

C#:
public class Class1
{
	public Class1(){}
	public static string CoffeeMaker(string strWater, string strBeans)
	{
	   string strCoffee = strWater+strBeans;
	   return strCoffee;
	}
}

Adding public static before the method allows that method to be accessed from outside of it’s class. Without those two keywords, you would only be able to use the method within it’s own class.

> Namespaces

This section discusses Namespaces, an organizational tool that can contain Classes or other Namespaces.

If methods are machines, and classes are factories, then Namespaces are neighborhoods. Namespaces serve a single purpose in C# – and that is organization. Essentially, you create name spaces to logically organize your code where classes alone don’t cut it.

A namespace can contain only classes or other namespaces. They’re particularly handy when there’s a possibility that you may have more than one class with the same name (which can cause all kinds of problems)… which is usually the case when working on a website that someone else created. Namespaces can also help keep you organized when have particularly large projects.

To create a namespace, use the following formula:

namespace [NameSpaceName] { [Contents] }

So, building on our previous examples, we might use a namespace to create a structure like this:

Namespace Example #1:
namespace MyNameSpace
{
   public class Class1
   {
       public Class1(){}
       public static string CoffeeMaker(string strWater, string strBeans)
       {
          string strCoffee = strWater+strBeans;
          return strCoffee;
       }
    }
}

Now if we needed to use CoffeeMaker() somewhere else in our project, we would just access it by using it’s full path (which isn’t really isn’t much different than the file system in your Windows operation system)…

Namespace Example #2:
string strCoffeePot = MyNameSpace.Class1.CoffeeMaker("water","beans");

We’ll discuss this more in the next section.

> Object Oriented Programming

This section uses previous sections in this article to explain how OOP concepts apply to C#.

This is where most C# tutorials would start, but I’ve decided to put it at the end. I don’t expect you to retain absolutely everything you read so far… at this point, you should have at least a general grasp of how C# code is structured (sort of like a file system)…

At the lowest level are your statements.
Statements go instead methods (and sometimes the class itself, if appropriate).
Methods go inside classes.
And namespaces contain either classes or other namespaces.

The important concept here is the idea of objects. Almost everything in C# can be considered an object – and any object can contain other objects. Any time you need to access an object that is inside another object, you use a period ( . ) – it’s almost exactly the same as using a forward-slash to access folders on a website.

Tip: Visual Studio will help you with this. If you type the name of an object, then hit period, Visual Studio will pop up a list of all the available objects and properties within that object.

This concept extends to just about everything in ASP.NET – including web controls (which will be discussed in a future article).

> The .NET Framework

This section discusses the .NET Framework, and how it can make your programming life easier.

The .NET Framework is simply a huge collection of namespaces and classes that Microsoft has created to make your life easier (particularly when it comes to doing common programming tasks).

For instance, if you want to write some code to send an email – there’s a class to help you do that. If you need to do some calculations involving dates – there’s a class to help you do that, too. Do you want to some fancy stuff with strings? Yes, there’s a already a class to help you with that, too. Don’t be afraid to poke around and see what’s available.

You should bookmark the Library section of http://msdn.microsoft.com – it’s loaded with fantastic resources regarding the .NET Framework and what it can do to help you out.

Whew, that article turned out to be a LOT bigger than I had planned… but hopefully you now have a working understanding of how C# code is structured. Play around with what you’ve learned, see what you can do with it. The best teaching is the teaching you give yourself.

Our next tutorial will introduce conditionals – if statements, if/else statements, and switch statements.

No Comments

Post a Comment

You must be logged in to post a comment.

RSS Twitter LinkedIn Facebook
Doing neato things with JavaScript, please wait...