I’m Learning C# – Part 7

It’s a long time since our last post on learning C#. So I thought to use this post as some kind of a refresher with some additional inputs.

Remember in the beginning of each code, we have used using System; Now System is a namespace which contains Console.WriteLine and Console.ReadLine that we used later in our code. So if we do not have the same first line, we could also use System.Console.WriteLine and System.Console.ReadLine instead. Console is a class inside System and WriteLine and ReadLine are methods inside them. Curious to know more – check out this link. Your namespace ensures that whatever methods, classes, variables you create inside of it, doesn’t meddle with other namespaces anywhere else. That’s the importance of having your own namespace, organizes things.

  1. Okay, now ever wondered what to do if you forgot the syntax of a loop, say for loop. Very simple, just type in for then click tab twice. Visual studio will do automatic filling for you 🙂 
  2. For debugging, use F5, F9, F10, F11.
  3. Declare variables as and when you need them. Don’t list everything on the top.
  4. Your machine code is found inside the bin folder -> debug of your project.

A small bit of an array snippet so that we stick to coding.

int[] array = new int[5]; // this is the array declaration
for (int i = 0; i < array.Length; i++) // length of the array is 5
{
array[i] = 2 * i;
Console.WriteLine(array[i]);

}
Console.ReadLine();

Now 2 ways to loop through the elements of an int array and a string array are given below:

int[] array = new int[] { 1,2,3,4,5};
for (int i = 0; i < array.Length; i++)
{
array[i] = 2 * i;
Console.WriteLine(array[i]);

}
foreach (int item in array)
{
Console.WriteLine(item);
}

string[] str = new string[] { “hi”, “hello”, “3”, “ok” };
for (int i = 0; i < str.Length; i++)
{
Console.WriteLine(str[i]);
}

foreach (string item in str)
{
Console.WriteLine(item);
}
Console.ReadLine();

We can make use of a simple for loop or we could you a foreach loop

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s