Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace ArrayOfObjects
- {
- class Program
- {
- static void Main(string[] args)
- {
- Class1[] listing = new Class1[3]; // Alex: okay, the array of 3 instances of Class1 is declared. Everything's perfectly fine
- // Alex: Juan. Looks great
- Class1 a1 = new Class1();
- a1.YourName = "Juan";
- a1.YourAge = 26;
- a1.YourCountry = "Argentina";
- // Alex: That would be me. Still fine
- Class1 a2 = new Class1();
- a2.YourName = "Alex";
- a2.YourAge = 20;
- a2.YourCountry = "Russia";
- // Alex: Our old pal Jon this was intended to be
- Class1 a3 = new Class1();
- a2.YourName = "Jon Skeet"; // Alex: uh-oh, should've used a3 here.
- a2.YourAge = 40; // Alex: and here as well. That's how I ended up being 40. :D
- a2.YourCountry = "USA";
- /* Alex: I'll once again be boring and read a small lecture. :) While it is tempting to give variables short names
- (a1, a2, a3 and the like), I think many guides do you a bad favor with giving you this habit. Variables with short, cryptic,
- meaningless names are the main cause to mistakes like one above (I guess here that it was a mistake, and Jon Skeet should've
- been assigned to a3 instead of a2). You really should try and give your variables more meaningful names: even though they're
- longer to type, they make the code much more obvious. Consider the following: */
- Class1 juan = new Class1();
- juan.YourName = "Juan";
- juan.YourAge = 26;
- juan.YourCountry = "Argentina";
- Class1 alex = new Class1();
- alex.YourName = "Alex";
- alex.YourAge = 20;
- alex.YourCountry = "Russia";
- Class1 jonSkeet = new Class1();
- jonSkeet.YourName = "Jon Skeet";
- jonSkeet.YourAge = 40;
- jonSkeet.YourCountry = "USA";
- /* Alex: Nothing has changed logic-wise, but the code got somewhat more understandable and much less error-prone. */
- // a1 and a2 are references to objects in memory
- listing[0] = a1;
- listing[1] = a2;
- //Alex: dont' know what your intention was, but I'd put the a3 into the array too. It has room for 3 instances anyway
- listing[2] = a3;
- //listing[1].Print();
- // Alex: this works so nicely. You'll love it even more when it'll come to inheritance/polymorphism (just teasing)
- for (int i = 0; i < 2; i++)
- {
- listing[i].Print();
- }
- Console.ReadLine();
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace ArrayOfObjects
- {
- class Class1
- {
- // We define our properties
- public string YourName { get; set; }
- public int YourAge { get; set; }
- public string YourCountry { get; set; }
- public void Print()
- {
- //we are making use of string formatting syntax
- Console.WriteLine("{0} with age {1} from {2} ", YourName, YourAge, YourCountry ); // Alex: string formatting rocks!
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement