I’m Learning C# – Part 11

In this lesson, we are going to use enum and switch together.

class Program
{
static void Main(string[] args)
{
List<doc> DocList = new List<doc>()
{
new doc {name =”first”, status = testStatus.Created, number= 1},
new doc {name =”second”, status = testStatus.Review, number= 2},
new doc {name =”third”, status = testStatus.Approval, number= 4},
new doc {name =”forth”, status = testStatus.Released, number= 4},
new doc {name =”fifth”, status = testStatus.Obsolete, number= 5},
};
foreach (var item in DocList)
{
switch (item.status)
{
case testStatus.Created:
Console.ForegroundColor = ConsoleColor.White;
break;
case testStatus.Review:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case testStatus.Approval:
Console.ForegroundColor = ConsoleColor.Cyan;
break;
case testStatus.Released:
Console.ForegroundColor = ConsoleColor.Green;
break;
case testStatus.Obsolete:
Console.ForegroundColor = ConsoleColor.Red;
break;
default:
break;
}
Console.WriteLine(“the name is {0} and status is {1}”, item.name, item.status);

}
Console.ReadLine();
}
}

class doc
{
public string name {get; set;}
public testStatus status {get; set;}
public int number {get; set;}
}

public enum testStatus
{
Created,
Review,
Approval,
Released,
Obsolete
}

Enum is used when we want to restrict the values that a particular parameter can take. In this case, we want to limit the status to Created, Review, Approval, Released or Obsolete.

The switch, depending on the status, changes the ForegroundColour of the console as can be seen in the output below:

capture

Isn’t that lovely 🙂

What if we encounter an exception during run time?

In that instance, we make use of the try catch block.

try
{
var content = File.ReadAllText(@”C:\google.txt”);
Console.WriteLine(content);
}
catch(FileNotFoundException e)
{
Console.Write(e.Message);
}
Console.ReadLine();

With this post, I am pretty much wrapping up the C# sessions.

Do comment on areas I haven’t covered and maybe I will write another post 🙂

Advertisements

I’m Learning C# – Part 10

The following is a code to determine how many days have passed since I was born.

DateTime current = DateTime.Now;
DateTime myBirthday = DateTime.Parse(“1900, 01, 13”);
TimeSpan today = current.Subtract(myBirthday);
Console.WriteLine(today);

or

DateTime today1 = DateTime.Now;
DateTime birthday = DateTime.Parse(“1900,01,31”);
TimeSpan interval = today1 – birthday;
Console.WriteLine(interval);
Console.ReadLine();

We are using DateTime which is part of a struct. Again we are using TimeSpan which is part of another struct. You don’t need to by heart all these. Highlight the term you want to know about, clikc F12, it will take you to the definition of that term in Reference Source.

Now a little about the static keyword.

I have a class car which has a method price1() which is static.

class car
{
public int number { get; set; }
public string colour { get; set; }
public string make { get; set; }

public static double price1()
{
double value = 1;
return value;
}
}

To access this method inside my main method, all I have to do is

Console.WriteLine(“{0}”,car.price1());
Console.ReadLine();

Instead if I didn’t have the static word, I would have had to create an instance of car (an object) and use it access the method.

class car
{
public int number { get; set; }
public string colour { get; set; }
public string make { get; set; }

public double price1()
{
double value = 1;
return value;
}
}

Then my code in main() should be

car myCar = new car();
Console.WriteLine(“{0}”,myCar.price1());
Console.ReadLine();

See the difference 🙂

There are different ways to initialize the number, colour and make of the car.

car myCar = new car();
myCar.number = 8123;
myCar.make = “Maruti”;
myCar.colour = “Black”;

or

car myCar2 = new car() { number = 123, make = “jazz”, colour = “white” };

Now to manually delete an object you created, set it’s value to null

myCar2 = null;

The .Net Framework has a garbage collector which will remove all references to memory once the object life is completed or out of scope.

The following is how to define a List and intialize values to it. List is found in System.Collections.Generic so you need to add it in the using.

List<car> List1 = new List<car>()
{ new car(){ number = 1223, make = “honda”, colour = “yellow” } };

How to Become Bad

All I wanna do is just drink drink drink

And then go out for a smoke smoke smoke

You might think what am just blabbering

Because this is all I know how to become bad.

I asked my girl if I could get a tattoo

She asked me back why I wanted to

I told her that’s how am planning to become bad

She gave me a huge lecture that was a huge bang.

All day I think of ending myself

Or think, ‘better I wait for WW3’

Well neither of the two does actually happen

Then I start cribbing and sobbing about it.

 

The Sarpa Kavu at My Ancestral Home

My ancestral home brings me this nostalgic feeling, I’m miles and miles away from my ancestral home but the thoughts and memories surrounding it seems to remain so fresh akin to a newly blossomed flower.

I am a huge fan of mythical beings like witches, vampires, lycans, magic and all those stuffs that keep you enthralled because you really don’t know if there was any truth in them. Again I am absolutely fascinated by the mythology of different religions, how the stories blend so well, how they maintain continuity and the vast extend to which it was able to capture people that they still preach from them, follow them, write, discuss and debate about it. The thought process, the way the stories are told are beyond any one of today. Imagine the most famous book of today, maybe Harry Potter or Lord of the Rings or let’s say Shakespearean texts. After a 1000 years, will anyone still be discussing about them? I really doubt that. But these traditions and customs that are imbibed with religion, they surely are going to survive the test of time.

Anyway, my ancestral home which no more exists with the same glory of past years is where I wish to start talking about. I am not talking about the home, it was a normal home with thatched roofs and many cool rooms even at the peak of summer. The home was surrounded by a dense forest kind of plantation where different trees grew with many birds around. The crows and the cuckoos and the squirrels and the rats 😀 It was so close to nature that today if you visit a zoo, you would see less of  fauna and flora comparatively.

In that dense forest was (and it is still there) a tree, a very old  and large one. It was so tall I used to think it was touching the skies. It had a very big bark, it would take 6-8 little hands to wrap around it once. It was always full of leaves but the leaves were at such heights I really didn’t know how they looked like until they fell down all dry and crumbled.

Now this tree used to have a sarpa kavu (abode of snake) adjacent to it. My ancestors had bought this land from the then inhabitants of the place who used to worship the snakes. They used to have this poojas to feed and please the snakes by offering milk and other offerings, you know the usual deity offerings. After they sold the land, which was some 6-7 generations of me, no one from my ancestors actually bothered about the tree and the sarpa kavu. It was there somewhere in the forest, and none of us went anywhere near it. We were actually forbidden from doing so, with some tales of snakes following us and biting us or bringing bad luck if we disturbed that area. Also not to go anywhere around it after 6 pm. Truth or myth, we followed just like we follow all our traditions and rituals without even knowing the significance of it.

When I was a kid, I belonged to the naughty kid category and so along with my cousins I have went as far as near the tree and touched it with my bare hands. My cousins had shouted at me and warned me that they would inform the elders leading to some small favours I had to do so as to avoid the secret from coming out. That’s fun, isn’t it?

In the recent years, the relatives who are currently owners of the land where the tree is, wanted to cut down the tree for money as they were in some financial crunches. Generations later, we always have this thought process, all the stories are fake, hence why not go ahead and cut it down. Still, a saint and a priest were called to get their opinions. (Ya, in matters of religion, it is always better to get opinions from people of different religion).

This meet up led to the shedding of more shocking information. The tree in question is the living abode of a king Naga and there is a Nagamanikyam, a precious gem costing millions under the tree which the Naga is protecting so if anyone dares to cut the tree, him and all will go through the wrath of Naga and all snakes and will be burnt to death. This instilled so much fear in all of us, we decided to find some other way to get money forget cutting it.

The greed for gem prompted us to ask the inevitable question, ‘so will we ever get the gem if we don’t disturb the tree?’ The answer was, I don’t know if it is true or false or just a getaway answer. It was, ‘as long as the Naga is protecting the gem, the tree will be alive, it can be 100 years, 500 years or a 1000 years. After that the Naga will leave and the tree will dry out on its own. At that time, whoever owns the land can clear the tree and its surrounding. now about the gem, the Naga will decide whether to leave the gem to the owners (our future generations) or to take it with him, no one knows for sure’. This is like the funniest answer we had ever heard.

In short, the present generation should have no hope to harness the riches of the gem, a future generation down the line could 🙂

I’m Learning C# – Part 9

The best way to learn or I must say use a blend of loops is by creating patterns. Here I made a diamond of “*”. Try for yourself

class Programcapture
{
static void Main(string[] args)
{

StringBuilder newstring = new StringBuilder();
for (int i = 0; i <= 10; i++)
{
int k = i;
while(k<10)
{
newstring = newstring.Append(” “);
k++;
}

for (int j = 0; j <= 2*i; j++)
{
newstring = newstring.Append(“*”);
}
newstring = newstring.Append(“\n”);

}
for (int i = 9; i >= 0; i–)
{
int k = i;
while (k < 10)
{
newstring = newstring.Append(” “);
k++;
}

for (int j = 0; j <= 2 * i; j++)
{
newstring = newstring.Append(“*”);
}
newstring = newstring.Append(“\n”);

}
Console.WriteLine(newstring);
Console.ReadLine();
}
}

Changing the numbers here and there and playing with the loops will get you many more patterns 🙂

Things which are new here is StringBuilder. It’s a class included in System.Text and it is sealed class which means you cannot inherit it. Now we have created an object of the type StringBuilder called ‘newstring’ to do our appending. Now this method will be effective when we have lot of appending to be done to reduce the strain on memory.

I’m Learning C# – Part 8

Today we will learn how to reverse a string.

Method 1: read from console into a string, assign it into a character array, use the reverse property of arrays and then write it to console.

string straight = Console.ReadLine();
char[] charnew = straight.ToCharArray();
Array.Reverse(charnew);
Console.Write(charnew);
Console.ReadLine();

Method 2: Assigning the reversed data read from the console and assigning it to the char array.

char[] charnew = Console.ReadLine().Reverse().ToArray();
Console.Write(charnew);
Console.ReadLine();

Converting to upper case along with reversal

char[] charnew = Console.ReadLine().ToUpper().Reverse().ToArray();
Console.Write(charnew);
Console.ReadLine();

Next let us learn to generate a random number. So this is a simple code which takes in any name and prints a random number between 1 and 50 as the age of the person.

class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Enter the name”);
string name = Console.ReadLine();
Console.WriteLine(“the age of {0} is {1}”, name,age(name));
Console.ReadLine();
}
static int age(string name)
{
Random randomAge = new Random(); // Random is the class and we are creating an object randomAge here
int rand = randomAge.Next(1, 50); // Next is a method defined in the class Random
return rand;
}
}

Now if we want a do-while loop for the above logic, lets try something like this

class Program
{
static void Main(string[] args)
{
bool x = true;
do
{
Console.WriteLine(“Enter the name”);
string name = Console.ReadLine();
Console.WriteLine(“the age of {0} is {1}”, name, age(name));
Console.WriteLine(“do you want to continue? 1 for yes; 0 for no”);
string response = Console.ReadLine();
if (int.Parse(response) == 1)
{
x = true;
Console.WriteLine(“continuing the loop”);
}
else
{
x = false;
Console.WriteLine(“exiting the loop”);
}

} while (x);
Console.ReadLine();
}
static int age(string name)
{
Random randomAge = new Random();
int rand = randomAge.Next(1, 50);
return rand;
}
}

“Even If It hurts You”

I will do what I want, Even if it hurts you

I will call your ‘friends’ bitch, Even if it hurts you

I will eat street food, Even if it hurts you

I will try to correct you, Even if it hurts you

You do What you want to do, Masala tea!!

——————————————-

You break the Decree, Even if it hurts me

Your level zero mentality is OK, Even if it hurts me

You lie black and white, Even if it hurts me

You take me for granted, Even if it hurts me

You do What you want to do, Masala tea!!

——————————————-

I get angry at your stupid logic, Even if it hurts you

I am super jealous of your popularity, Even if it hurts you

I don’t like you in Western attires, Even if it hurts you

I don’t like you in make overs, Even if it hurts you

You do What you want to do, Masala tea!!

———————————————

 

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

Learning to Drive A Car – Day 10

Oh finally the final day. How I wished it just ended.

Started, moved into traffic, spend 15 minutes in there. In that 3-4 times the car stopped. With this knowledge level, am I confident to take a car out? A big NO. Am I confident? Another big NO. Totally disappointed by the training offered.

I am actually wondering if all driving classes are taken in a similar fashion by other driving schools. See I mentioned another driver who taught well in one day. Am very thankful to that guy.

Maybe I had a wrong driver to teach. Imparting knowledge is an art. Only some can do it. The one who taught me certainly couldn’t.

I don’t know when is the next time I would lay hands on a car and improvise my meager learning. Anyway looking ahead for the opportunity.

Verdict: I wouldn’t recommend this driver to anyone.

Learning to Drive A Car – Day 9

The penultimate day of driving. It lasted 50 minutes. Nothing new. First and second gear. It was all about clutch brake maintain. I was able to cruise with minimal guidance on steering but am least sure of the clutch brake controls.

All through the drive, the driver was getting calls from the owner telling he didn’t pick another person at the same time, then he was explaining he called and it was out of reach and then he called that person and that person told he waited. Too much story leading to lack of concentration.

1 U turn, 1 reverse was done.

I just don’t know if this is all they teach in any driving school or is it just at this place. It’s like taking for the drive just to finish the hours. What’s the satisfaction that the driver gets? The satisfaction for imparting knowledge? I don’t think so. The satisfaction of having got all the money? Definitely yes!