Get up to 80 % extra points for free! More info:

Lesson 2 - First object-oriented application in C# - Hello object world

In the previous lesson, Introduction to object-oriented programming in C# .NET, we introduced the object-oriented programming and went over what makes it more efficient than any other programming methodology. We already know that objects have fields and methods. We also know that to create an object we'd have to create a class first. Remember that a class is a pattern according to which we create instances later.

As we did in the Basic constructs of C# .NET course we'll create what must always be done when you encounter a new paradigm in programming, a "Hello World" program. A Hello object world program, to be precise!

We'll start by creating a new Visual Studio console application. In the Solution Explorer, on the right, right-click on your project and select Add -> Class. You can also use the Shift + Alt + C shortcut.

Adding a new Class to a C# project in Visual Studio - Object-Oriented Programming in C# .NET

We'll name our class Greeter.cs and confirm. We name classes using CamelCase, meaning that the first letter in every word in the class name is capitalized and we don't write spaces. The name, of course, shouldn't contain any accent characters, if your native language uses any, you can use them in strings, but never in identifiers.

Declaring a new class in Visual Studio - Object-Oriented Programming in C# .NET

We're going to create a "greeter" object using this class later, which will be able to greet the user. You might've noticed by now that we're treating the program in a different way, for every action, there is some object responsible. One should not simply start by writing stuff into the Main() method. In our case, it may seem useless, but in more complex applications it'll prove to be more than worthwhile :)

Another .cs file will be added to our Solution Explorer and VS will open it for us. We can later return to the original Program.cs with the Main() method using tabs or via the Solution Explorer.

Let's take a look at what VS has generated for us and add a greeting method to the class.

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

namespace HelloObjects
{
    class Greeter
    {

    }
}

As methods are gathered into classes, classes are gathered into namespaces. They're also called packages in some languages. To make our class visible in Program.cs, where we have the Main() method, we'd have to give them a common namespace. Our class does it automatically, VS wraps new classes in the same namespace that the application is in. Instead of "HelloObjects" you'll have your application name there. If you haven't named it manually, it will automatically name it ConsoleApplica­tion1.

Using allows us to make classes from other namespaces accessible so we could work with them. Basically, VS will prepare classes for us using the System namespace, then generic collections, Linq and Text namespaces. The System namespace is the most important for us since it contains the Console class. We'll use the other ones later mentioned and then some, especially for working with text files.

In the namespace, there's our class declared by the class keyword. The class is named Greeter and it's empty.

Notice that the code is almost the same as in Program.cs. We now understand what we looked over in the previous course. Our console program was actually a class containing the Main() method, and this class was placed in a namespace. You see, in C#, there is no real way of creating "non-OOP programs", which is a good thing :)

Next, we'll add a Greet() method to the Greeter class, which will be publicly visible and won't return a value or take any parameters.

In C# .NET, we declare methods as follows:

[Access modifier][return type][MethodName]([parameters])

We'll write an access modifier before the method, which in our case is public. If we omit the modifier, C# will assume it is a private, non-public, method. To make the method not return a value we must declare the method using the void keyword. Followed by the method's name, which we will write in CamelCase as well. Parentheses with parameters are required, we'll leave them empty since the method won't have any parameters. In the method body, we'll write code that prints a message to the console.

Our class will now look like this:

class Greeter
{

    public void Greet()
    {
        Console.WriteLine("Hello object world!");
    }

}

That's all we'll do for the class for now. Let's move on to Program.cs.

We'll create an instance of the Greeter class in the Main() method body. Which will be a greeter object that we'll be able to work with. We store objects in variables and use the class name as the data type. Instances usually have the same name as classes, but with the first character in lowercase. Let's declare the variable and then store a new Greeter class instance within it:

Greeter greeter;
greeter = new Greeter();

The first line says: "I want a variable named "greeter" that will later contain a Greeter instance". We've already worked with the variables like this.

The second line contains the new keyword which will create a new Greeter class instance. We assign this instance to our variable.

When a new instance is created, the constructor is called. The constructor is a special class method, that's why we write the empty parentheses when creating an instance, we're calling this "creation" method. The constructor usually contains some initialization of the object's internal state, e.g. it initializes the fields with default values. We haven't declared a constructor in our class, that's why C# created the implicit parameterless constructor. So creating an instance of an object is similar to calling a method. Of course, the entire code can be shortened to:

Greeter greeter = new Greeter();

Since now we have a Greeter class instance in a variable, we can let it greet the user. We'll call the Greet() method as greeter.Greet(). We will also add Console.ReadKey() into the application. The Main() method code will now look like this:

Greeter greeter = new Greeter();
greeter.Greet();
Console.ReadKey();

Let's run the program:

Your first object-oriented app
Hello object world!

You can run the program in our online compiler as well, just notice that all classes are in the same file there if you click on the code. It's simpler for our online samples, however, you keep classes in separated files in your projects. We have successfully made our first object-oriented app!

Now let's add a name parameter to our Greet() method, so it could greet the user properly:

public void Greet(string name)
{
    Console.WriteLine("Hi {0}", name);
}

The syntax of the method parameter is the same as the syntax of a variable. If we wanted more parameters, we'd separate them with commas. Let's modify our Main() method now:

Greeter greeter = new Greeter();
greeter.Greet("Carl");
greeter.Greet("Peter");
Console.ReadKey();

Our code is now in a method and we're able to call it multiple times with different parameters. We don't have to copy "Hi ..." twice. We'll separate our code logically into methods from now.

Console application
Hi Carl
Hi Peter

Let's add some field (attribute) to the class, e.g. a text where the greeting will be stored. We declare fields as variables as well. We will also write an access modifier before them just like before otherwise C# would assume that they're private. Here's what your class should look like at this point:

class Greeter
{
    public string text;

    public void Greet(string name)
    {
        Console.WriteLine("{0} {1}", text, name);
    }

}

We have to initialize the text in the instance created in Program.cs:

Greeter greeter = new Greeter();
greeter.text = "Hi";
greeter.Greet("Carl");
greeter.Greet("Peter");
greeter.text = "Hello programmer";
greeter.Greet("Richard");
Console.ReadKey();

Console application
Hi Carl
Hi Peter
Hello programmer Richard

In object-oriented design, it's not recommended to let each object control the input and output, i.e. printing lots of stuff into the console. Each object should have a single responsibility and shouldn't exceed its purpose. Let's make our object solely responsible for creating the greeting text, and we'll move the printing outside the object, i.e. to the Main() method. The advantage to designing objects with a single responsibility is that they're then universal and reusable. Our object can only print text to the console now, but we'll change it so the method will only return the text and it'll be up to the recipient to decide what to do with it. Like this we could store greetings into files, print them on websites or process them further.

Since we want the method to return a string value, we'll change it from being a void type to a string type method. We use the return keyword to return a value. The return keyword terminates the method and returns the value. Any code in the method's body after the return will not be executed! Let's modify both classes:

The Greet() method in Greeter.cs:

public string Greet(string name)
{
    return String.Format("{0} {1}", text, name);
}

The Main() method body in Program.cs:

Greeter greeter = new Greeter();
greeter.text = "Hi";
Console.WriteLine(greeter.Greet("Carl"));
Console.WriteLine(greeter.Greet("Peter"));
greeter.text = "Hello programmer";
Console.WriteLine(greeter.Greet("Richard"));
Console.ReadKey();

Now, our code follows the guidelines of good OOP and over all programming practices. We will also add comments in our class accordingly. We'll add comments over the class name and over the name of each field and method. We'll use the triple slash to write comments "///", VS will then generate an XML, where we'll describe everything that's happening. Comments are useful when we make new class methods because its description will then be available to us in IntelliSense. We can collapse them comments by using small "-" buttons, if needed. A fully documented class might look something like this:

/// <summary>
/// A class represents a greeter whose purpose is to greet the user
/// </summary>
class Greeter
{
    /// <summary>
    /// Greeting text
    /// </summary>
    public string text;

    /// <summary>
    /// Greets the user with the stored greeting and his/her name
    /// </summary>
    /// <param name="name">The user's name</param>
    /// <returns>The greeting text</returns>
    public string Greet(string name)
    {
        return String.Format("{0} {1}", text, name);
    }

}

Let's check and see if VS actually displays descriptions we've set in IntelliSense:

Greeter object methods in Visual Studio - Object-Oriented Programming in C# .NET

Great! Our program already has some quality to it, despite it being relatively useless. If you want, you can try to create an object-oriented remake of our console calculator. In the next lesson, Solved tasks for OOP in C# .NET lesson 1-2, we'll program a simple game. We'll make two objects, warriors, compete in an arena, which will also be an object. See? Now you have something to look forward to! ;-)

In the following exercise, Solved tasks for OOP in C# .NET lesson 1-2, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 62x (36.03 kB)
Application includes source codes in language C#

 

Previous article
Introduction to object-oriented programming in C# .NET
All articles in this section
Object-Oriented Programming in C# .NET
Skip article
(not recommended)
Solved tasks for OOP in C# .NET lesson 1-2
Article has been written for you by David Capka Hartinger
Avatar
User rating:
11 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities