new C# class

Advertisements

Hello everybody,

Michael here, and today’s post will cover classes in C#.

What is a C# class? Better yet, what is a programming class in general?

If you’ve learned other programming languages, you’ll certainly have encountered this concept. However, in case you need a refresher, C#, like Java and Python (and possibly many other languages) is what’s known as an object-oriented programming language. Just like with Java and Python, everything comes in classes and objects. All those classes and objects come with their own methods and attributes.

new C# class

Now, how do we construct a C# class? Take a look at this example below:

class Cat
{
    string color = "orange";
    int age = 11;
    string gender = "male";

    static void Main(string[] args)
    {
        Cat orangeCat = new Cat();
        Console.WriteLine(orangeCat.age);

    }
}

11

In this simple Cat class, we have three attributes-color, age, and gender. We also created an object of the Cat class in the Main() (yes C# capitalizes the word Main) method called orangeCat and accessed its age attribute with the following code-orangeCat.age-which returns the value of 11.

  • To access any attribute of a C# object, remember the following syntax: objectname.attributename.

Easy enough right? Now let’s see some new C# class tricks!

new C# class (no default values)

Now, how do we create a C# class with no default values? Let’s take a look:

class NewCat
{
    string color;
    int age;
    string gender;

    public NewCat(string catColor, int catAge, string catGender)
    {
        color = catColor;
        age = catAge;
        gender = catGender;
    }

    static void Main(string[] args)
    {
        NewCat brownCat = new NewCat("brown", 11, "female");
        Console.WriteLine("This is a " + brownCat.color + " cat who is " + brownCat.age + " years old and is a " + brownCat.gender);

    }
}

This is a brown cat who is 11 years old and is a female

In this example, I didn’t declare default values for color, age, and gender. Instead, I used a special method called a constructor to allow any object of the Cat class to be initialized with any possible value for each attribute. The constructor must have the same name as the class (Cat in this case) and can contain as many parameters as you want (3 parameters in my case for color, age, and gender).

Notice how I still declared the color, age, and gender variables before the constructor even though I use these same three variables inside the constructor. Why might that be? The first time I mention color, age and gender, all I did was declare that these variables will be a part of this Cat class. However, when I mentioned them again in the constructor, I actually initialize them to whatever the values of catColor, catAge and catGender are set to in the parameters.

  • Remember that before you initialize a variable with a constructor, you must first declare it!
  • Even though I didn’t give any default values for each variable, I can still access each variable in the same manner I did in the previous example (e.g. objectname.attributename).
  • Yes, since I stored each example as a separate script in the same directory, I used the name NewCat for this class. Keep in mind that if you’re going to create multiple classes in the same directory, you must use different names for each class.

Here are the links to both of today’s scripts in my GitHub:

Thanks for reading,

Michael

For (A Lesson; On C#; Loops)

Advertisements

Hello readers,

Michael here, and today’s post will be all about loops in C#. We’ll go over the for-loop, foreach-loop and while-loop!

If you learned about loops through some of my previous programming tools, great! However, for those who may not know, loops in programming are simple sets of directions for the program to repeat X amount of times until a certain condition is met.

For (A Piece; On C#; Loops)

The first type of loop we’ll cover is a simple C# for loop. Here’s an example of a C# for loop:

for (int m = 5; m <= 30; m+=5)
{
    Console.WriteLine(m);
}

5
10
15
20
25
30

In this loop, I have the for (statement 1; statement 2; statement 3) with the respective statements being int m = 5 (setting initial loop value to 5), m <= 30 (setting the loop-ending condition to the point where m is less than or equal to 30), and m+=5 (indicating that m should be incremented by 5 during each loop iteration). After the for statement, I have the body of the loop, which prints out each successive value from 5 to 30 in increments of 5.

  • Just so you remember, the three statements in a C# for loop are (in order) the initial value-setter, the loop-ending condition, and the action that should be performed during each loop iteration. Also, the statements in the for loop need to be separated by semicolons.

Foreach (Lesson in Loops)

The next type of C# loop we’ll iterate through (coder joke) is the foreach loop. Here’s an example of a foreach loop below:

string[] states = ["Tennessee", "Florida", "California", "New Mexico", "Arizona", "Ohio", "Indiana"];

foreach (string s in states)
{
    Console.WriteLine(s);
}

Tennessee
Florida
California
New Mexico
Arizona
Ohio
Indiana

In this example, I’m iterating through the states array using the foreach loop. Unlike the for loop, the foreach loop only requires one statement-(array type element in array). In this statement, you’ll need to include the array type, indicator value for each element in the array (s in this case) and the name of the array. In this case, I used foreach (string s in states).

While (C# Loop Runs)

Last but not least, let’s explore C# while loops. You may recognize while loops from other programming tools you know about (like Python) and in C#, while loops do the same thing-run the loop over and over WHILE a certain condition is True.

Here’s an example of a simple C# while loop:

int o = 2;

while (o <= 100)
{
    Console.WriteLine(o);
    o *= 2;
}

2
4
8
16
32
64

In this example, we have a simple C# while loop that sets the initial value-o-to 2. The loop will then multiply o by 2 for each iteration until o hits the highest possible value allowed by the loop condition. In other words, o will keep multiplying itself by 2 until it gets to 64, as 64*2 (128) will end the loop as 128 is greater than 100.

Now, how would you structure a C# while loop? The syntax is quite simple-while (condition to keep loop running) { code block to execute }.

Do (Loop Code) While Loop = Running

So we just explored the C# while loop. However, did you know there’s a variation of the C# while loop called the do-while loop. It works just like a while loop with one major difference-do-while loops will always be executed at least once as they always check whether the condition is still true before performing the next loop iteration. Here’s our while loop example from above converted into a do-while loop

int f = 2;

do  
{
    Console.WriteLine(f);
    f *= 2;
} 
while (f <= 100);

2
4
8
16
32
64

How would you structure a do-while loop. Easy-do { code block to execute } while (condition to test loop)! As you can see from the output, our do-while loop returned the same six values as our while loop above.

For (Infinite; Loop; Encounters)

Yes, just as with other languages we’ve covered (Python and R for two), it is possible to have the infinite loop encounter in C# as well. Here’s an example of that:

while (true)
{
    Console.WriteLine("Michael's Programming Bytes");
}

The loop above is a simple example of an infinite C# loop. Since the while (true) statement will never stop the loop, it will just keep going, and going, and going…unless of course you write a break statement in the loop to stop it after X iterations or something like that.

For (Nested; Loops) For (In; C#)

Yes, it is possible to have nested loops in C#, just as it’s possible to have nested loops in other programming languages. Here’s a simple example of a C# nested loop:

for (int t = 2; t <= 20; t*=2)
{
    for (int n = 5; n <= 30; n+=5)
    {
        Console.WriteLine(t * n);
    }
}

10
20
30
40
50
60
20
40
60
80
100
120
40
80
120
160
200
240
80
160
240
320
400
480

This loop will print out all possible products of t and n through each iteration of the nested loop pair. The outermost loop-the one with t-runs first while the innermost loop-the one with n-runs second. The reason you see 24 outputs on this page is because the amount of iterations a nested loop has is the product of the amount of iterations for each individual loop. In this case, since the t loop runs four times and the n loop runs six times, we get 24 total iterations of the nested loop (4*6=24).

Here’s the link to the script for today’s post on my GitHub-https://github.com/mfletcher2021/blogcode/blob/main/Loops.cs. Note that I did include the infinite loop example here but if you want to effectively test the other loops, you can “turn off” the infinite loop simply by commenting it out of the code.

Thanks for reading,

Michael