|
|
Later Today: ASP.NET Tutorial 2: Introduction to C#
ASP.NET Tutorial 2: Introduction to C# (Structure)
by Matt on 2009/11/17 at 5:15 pm
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. > SetupThis 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 WebsiteTo 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.
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 ( VWD will automatically put together a very basic website for you. If you’re using VS2010, it will look like this ( ![]() Visual Studio 2010 Ultimate - An Open Project > Statements, Blocks, KeywordsDiscusses statements and blocks, C#’s most basic organizational concepts.
StatementsJust like the english language, C# has sentences – only they’re called statements and end with a semicolon ( ; ) instead of a period. Statements are generally short and simple, either setting or modifying data in some way. To do more complicated tasks, you simply write more statements that build upon what the previous ones accomplished – it’s just like grouping english sentences into a paragraph. Below is an example of a very simple statement – don’t worry about what it means just yet, we discuss that further down: C#:
int iMyNumber = 3; White Space & Ending StatementsIt is very important not to forget the semicolon when you finish a statement. As a rule, C# ignores white space, allowing you to split up a long statement to cover multiple lines (allowing you the freedom to organize and format your code however works best for you). For instance, the code in this next example is exactly the same as the previous example: C#:
int iMyNumber =
3;
OperationsWe’ll discuss this in more detail over time, but one key detail about statements is that they always function right-to-left. Look at the above statement example for a second, notice this follows the logic of ThingOnLeft Equals ThingOnRight. The equals sign in this statement ( = ) is called an operator. In C#, the code on the left side of the operator (in the previous example, this would be int iMyNumber) always refers to and relies on the code on the right side (in the above example, this is the number 3), never the other way around. We’ll cover operators more in the next article (there are a handful of operators, and each does something different), but for now just keep this one rule in mind: The left side of a statement always refers to the right side of a statement. BlocksIn C#, blocks come in many forms – conditionals, classes, namespaces, methods, etc. Generally, you can recognize a block because it uses curly braces ( { } ) to surround one or more statements. Below is just one example of a block: C#:
void MyMethod()
{
int iMyNumber = 3;
}
For now, you don’t need to understand what the block above represents (we’ll discuss it in a minute), since blocks come in many forms. Just remember that blocks are used to group code and curly-braces means you’re using a block. KeywordsIn C#, there are certain words that are reserved, because they serve a specific function within the language. These are called keywords, and you can only use them for their intended purpose. Hence, when you name an object (such as a variable, method, class, etc), your name can never be the same as a C# keyword. Tip: Visual Studio will let you know if you’re using a keyword by coloring the word blue. Keywords will also appear in Visual Studio’s intellitext popup as you type. Here’s a very small sample of keywords and what they do:
Don’t worry about this too much, Visual Studio is smart and will warn you immediately when you’ve made a mistake. Remember those red, wavy underlines that Microsoft Word uses? They’re in Visual Studio, too. If you see them, simply hover your mouse over the underlined code and a popup will tell you what the problem is (or rather, what it appears to be). The rule of thumb is: if the word turns blue when you type it, it’s a keyword and can’t be used to name something. > VariablesThis section discusses variables, one of the most basic components of any programing language.
DescriptionVariables 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.” DataTypesAt 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:
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. ReviewIn 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. > MethodsThis 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 MethodsThe 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 MethodsThe 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 ValuesMethods 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, > ClassesThis 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 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 ClassesIn 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 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 ClassesWhat 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:
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; /// 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. > NamespacesThis 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 ProgrammingThis 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. 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 > The .NET FrameworkThis 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