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

C# .NET OOP First object-oriented application in C# - Hello object world

In the previous lesson, Introduction to object-oriented programming in C# .NET, we introduced what object-oriented programming was 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

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. 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

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, a class has been located, which is 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.

Method declaration in C# .NET is the following:

[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. Objects are stored in variables where the class name is used 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 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. A constructor is a special class method, for which we write empty parentheses after the class name since we're calling the "creation" method. A constructor usually contains some initialization of the object's internal state, e.g. it initializes its fields with default values. We haven't declared a constructor in our class, that's why C# created the implicit parameterless constructor. Creating the object's instance 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 a 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 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. Fields are defined 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 is not recommended to let each object control input and output, i.e. printing lots of stuff into the console. Each object should have a duty to fulfill and shouldn't overlook its limitations. Let's make our object solely responsible for the greeting part, we'll print outside the object, i.e. in the Main() method. The advantage to designing objects with a single responsibility is that they're then universal and reusable. The object can only output 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 know what to do with it. We could also 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. Return terminates a method and returns a 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

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, RollingDie in C# .NET - Constructors and random numbers, 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! ;-)


 

Download

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

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
2 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 College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Activities (17)

 

 

Comments

Avatar
Olatunji Segun Yusuf:4/6/2017 11:38

Awesome way to start oop!
nice job!

 
Reply 4/6/2017 11:38
Avatar
Cameron M Marston:11/2/2017 3:26

Great info!

 
Reply 11/2/2017 3:26
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

2 messages from 2 displayed.