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” } };

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