Home » Gaming » Learn C# for Android part 2 – Classes and loops (also: rabbits!)

Learn C# for Android part 2 – Classes and loops (also: rabbits!)

Learn C# Coding

In part one of this Android tutorial series on learning C#, we looked at the absolute basics of C# programming. We covered methods (groups of code that perform specific tasks), some basic syntax (such as the need for semi colons), variables (containers that store data), and “if statements” for flow control (branching code that’s dependent on the values of variables). We also saw how to pass variables like strings as arguments between methods.

You should go back and take a look at that if you haven’t read it already.

At this point, you should be able to make some basic console apps, like quizzes, apps that store data, or calculators.

Learn C# for Android

In part two, we’re going to get a little more ambitious, covering some more basics — like loops — and exploring how to create and interact with classes. That means we’ll be able to start taking a stab at Android development and see how to bridge that gap. Continue reading if you want to truly learn C#!

Understanding classes and object oriented programming

Briefly in part one, we explained the basics of Object Oriented Programming, which revolves around languages using “classes” to describe “objects.” An object is a piece of data, which can represent many things. It could be a literal object in a game world like a spring, or it could be something more abstract, like a manager that handles the player’s score.

A single class can create multiple objects. So you might write one “enemy” class, but be able to generate an entire level full of bad guys. This is one of the big benefits of using object oriented programming. Otherwise, the only way to handle the behavior of a multitude of enemies would be to use lots of individual methods, each one containing instructions for how the bad guy should behave in different circumstances.

C# coding programming

If this is still a bit tricky to get your head around, all you really need to know is that objects have properties and behaviors. This is just like real objects. For instance, a rabbit has properties like size, color, and name; and it has behaviors, like jumping, sitting, and eating. Essentially, properties are variables and behaviors are methods.

The program we built in the last lesson is an example of a class too. The “object” we’re describing here is some kind of password control system. The property it has is the string UserName, and the behavior it has is NewMethod (checking the name of the user and greeting them).

Programming Learn C#

If that’s still a bit confusing, the only way to get our heads around is create a new class or two ourselves!

Creating a new class

If you’re going to learn C#, you need to know how to make new classes. Fortunately, this is very easy. Just click the Project menu item and then select “+Add Class.”

C# add class

Choose “C#” and call it “Rabbit.” We’re going to use this class to create conceptual rabbits. You’ll see what I mean in a moment.

If you check in your Solution Explorer on the right, you’ll see that a new file called Rabbit.cs has been created right beneath Program.cs. Well done — that’s one of the most crucial things to know if you want to learn C# for Android!

The new Rabbit.cs file has some of that same “boilerplate” code as before. It still belongs to the same namespace, and it has a class with the same name as the file.

namespace ConsoleApp2 {     class Rabbit     {     } }

Now we’re going to give our rabbit some properties with what we call a “constructor.”

Rabbit class C#

A constructor is a method in a class that initializes the object, allowing us to define its properties when we first create it. In this case, here’s what we’re going to say:

namespace ConsoleApp2 {     class Rabbit     {         public string RabbitName;         public string RabbitColor;         public int RabbitAge;         public int RabbitWeight;         public Rabbit(String name, String color, int age, int weight)         {             RabbitName = name;             RabbitColor = color;             RabbitAge = age;             RabbitWeight = weight;         }     } }

This allows us to create a new rabbit from a different class, and define its properties as we do:

Rabbit Rabbit1 = new Rabbit(“Jeff”, “brown”, 1, 1);

Now I realize in retrospect weight should probably have been a float or a double to allow for decimals, but you get the idea. We’re going to round our rabbit to the nearest whole number.

You’ll see as you write your rabbit out, you’ll be prompted to pass the correct arguments. In this way, your class has become a part of the code almost.

Believe it or not, this code has created a rabbit! You can’t see your rabbit because we don’t have any graphics, but it is there.

And to prove it, you can now use this line:

Console.WriteLine(Rabbit1.RabbitName);

This will then tell you the name of the rabbit you just created!

Learn C# Rabbit Weight

We can likewise increase the weight of our Rabbit, like so:

Rabbit1.RabbitWeight++; Console.WriteLine(Rabbit1.RabbitName + " weighs " + Rabbit1.RabbitWeight + "kg");

Note here that adding “++” on the end of something will incrementally increase its value by one (You could also write “RabbitWeight = RabbitWeight + 1”).

Because our class can make as many rabbits as we like, we can create lots of different rabbits, each with their own properties.

Adding behaviors

We might then also choose to give our rabbit some kind of behavior. In this case, let’s let them eat.

C# objects classes learn

To do this, we would create a public method called “Eat,” and this would make an eating sound, while also incrementally increasing the weight of the rabbit:

public void Eat()         {             Console.WriteLine(RabbitName + ": Nibble nibble!");             RabbitWeight++;         }

Remember,”public” means accessible from outside the class, and “void” means the method doesn’t return any data.

Then, from inside Program.cs, we will be able to call this method and this will make the rabbit of our choice eat and get bigger:

Console.WriteLine(Rabbit1.RabbitName + " weighs " + Rabbit1.RabbitWeight + "kg"); Rabbit1.Eat(); Rabbit1.Eat(); Rabbit1.Eat(); Console.WriteLine(Rabbit1.RabbitName + " weighs " + Rabbit1.RabbitWeight + "kg");

That will cause Jeff to eat three times, then we’ll hear it and be able to see he has gotten bigger! If we had another rabbit on the scene, they could eat as well!

Console.WriteLine(Rabbit1.RabbitName + " weighs " + Rabbit1.RabbitWeight + "kg"); Console.WriteLine(Rabbit2.RabbitName + " weighs " + Rabbit2.RabbitWeight + "kg"); Rabbit1.Eat(); Rabbit1.Eat(); Rabbit2.Eat(); Rabbit2.Eat(); Rabbit1.Eat(); Console.WriteLine(Rabbit1.RabbitName + " weighs " + Rabbit1.RabbitWeight + "kg"); Console.WriteLine(Rabbit2.RabbitName + " weighs " + Rabbit2.RabbitWeight + "kg");

At it like rabbits

This isn’t a particularly elegant way to handle lots of objects, as we need to write out the commands for each rabbit manually and can’t dynamically increase the number of rabbits as far as we want. We don’t just want to learn C# — we want to learn how to write clean C# code!

Objects collections learn C#

This is why we might use a list. A list is a collection; variable itself that basically contains references to other variables. In this case, we might make a list of Rabbits, and the good news is that this is very easy to understand:

List<Rabbit> RabbitList = new List<Rabbit>(); RabbitList.Add(new Rabbit("Jeff", "brown", 1, 1)); RabbitList.Add(new Rabbit("Sam", "white", 1, 2));

This creates the new rabbit as before, but simultaneously adds the rabbit to the list. Equally, we could say this:

Rabbit Rabbit3 = new Rabbit("Jonny", "orange", 1, 1); RabbitList.Add(Rabbit3);

Either way, an object has been created and added to the list.

We can also conveniently and elegantly return information from our rabbits list this way:

foreach (var Rabbit in RabbitList)             {                 Console.WriteLine(Rabbit.RabbitName + " weighs " + Rabbit.RabbitWeight + "kg");             }

As you might be able to figure out, “foreach” means you repeat a step once for every item in the list. You can also retrieve information from your list like this:

RabbitList[1].Eat();

Here “1” is the index, meaning you are referring to the information stored at position one. As it happens, that’s actually the second rabbit you added though: because lists in programming always start at 0.

Fibonacci

In case you hadn’t yet guessed, we’re now going to use all this information to create a Fibonacci sequence. After all, If you’re learning C# for Android, you should to be able to actually do something interesting with all that theory!

learn C# development

In the Fibonacci sequence, rabbits are shut in a room and left to breed. They can reproduce after one month, at which point they are sexually mature (I cannot confirm if this is correct Rabbit biology). If each rabbit couple can produce once per month from then on, producing two offspring, here’s what the sequence looks like:

1,1,2,3,5,8,13,21,34

Magically, each number in the sequence is the value of the previous two numbers added together. According to science, this is kind of a big deal.

The cool thing is, we can replicate that.

First, we need to introduce a new concept: the loop. This simply repeats the same code over and over again until a condition is met. The “for” loop lets us do this by creating a variable, setting the conditions we want to meet, and then operating on it — all defined inside brackets:

for (int months = 0; months < 100; months++)             { //Do something             }

So we are creating an integer called months, and looping until it’s equal to 100. Then we increase the number of months by one.

Want to see how this can become a Fibonacci sequence? Behold:

namespace ConsoleApp2 {     class Program     {            static void Main(string[] args)         {             List<Rabbit> RabbitList = new List<Rabbit>();             RabbitList.Add(new Rabbit("Jeff", "brown", 0, 1));             RabbitList.Add(new Rabbit("Sam", "white", 0, 1));                        for (int months = 0; months < 10; months++)             {                 int firstRabbit = 0;                 int timesToReproduce = 0;                 foreach (var Rabbit in RabbitList)                 {                     Console.Write("R");                     if (Rabbit.RabbitAge > 0)                     {                         if (firstRabbit == 0)                         {                             firstRabbit = 1;                         } else                         {                             firstRabbit = 0;                             timesToReproduce++;                         }                     }                     Rabbit.RabbitAge++;                 }                 for (int i = 0; i < timesToReproduce; i++)                 {                     RabbitList.Add(new Rabbit("NewBabyRabbit", "brown", 0, 1));                     RabbitList.Add(new Rabbit("NewBabyRabbit", "brown", 0, 1));                     Console.Write("r");                     Console.Write("r");                 }                   Console.WriteLine("  --- There are " + RabbitList.Count / 2 + " pairs of rabbits!");                   Console.WriteLine("");             }             Console.WriteLine("All done!");             Console.ReadKey();         }     } } 

Okay, that was harder than I thought!

I’m not going to go through all of this, but using what you’ve already learned, you should be able to reverse engineer it.

There are definitely more elegant ways of doing this — I’m no mathematician. However, I think it’s a fairly fun exercise, and once you can do it, you’re ready for the big time.

I’d love to see any other approaches, by the way!

Where do we go from here? How to learn C# for Android

With all that knowledge under your belt, you’re ready to start on bigger things. In particular, you’re ready to take a stab at Android programming with C# in Xamarin or Unity.

Learn C# for Android

This is different because you’ll be using classes provided by Google, Microsoft, and Unity. When you write something like “RigidBody2D.velocity” what you’re doing is accessing a property from a class called RigidBody2D. This works just the same, the only difference is you can’t see RigidBody2D because you didn’t build it yourself.

With this C# under your belt, you should be ready to jump into either of these options and have a big head start when it comes to understanding what’s going on:

In an upcoming lesson, we’ll also look at how you can take a U-turn and use this to build Windows apps instead!

Source of the article – Android Authority