clarification of the following code

Hi, i was wondering if someone would be kind enough to read over this code i have copied from a tutorial and check to make sure that the things i have listed in comments are correct + clarify where i have placed a "?".

thanks very much in advance



(bit of a greenhorn at this so sorry if im asking stupid questions)

using System;

namespace ConsoleApplication1
class Program
static void Main(string[] args) //program begins here
Car car;
//creating an object called car from Car class

car = new Car("Red"); //declaring its colour red

car = new Car("Green"); // declaring it green

Console.ReadLine(); //allows user to c writeline


class Car
private string color;

//settin up a private variable of type string

public Car(string color) // a method?
this.color = color; //?

public string Describe() // describe method?
return "This car is " + Color; //?

public string Color

// is this where the colour is set?
get { return color; }
set { color = value; }


  • [b]//program begins here[/b]
    - Yes, this is called an entry point. Some additional research for you would be to read about .net "assemblies" and "assembly entry point"

    [b]//creating an object called car from Car class[/b]
    - Almost, here a variable/reference is being made here, but no value is being assigned to it yet. It's almost like telling your application "get some memory ready to hold a Car - and know that whenever I say 'car' that I am referencing that memory".

    [b]//declaring its colour red[/b]
    - Partially. Here is where an object is being created from the Car class. Here you are saying "fill in the memory reserved for 'car' with an actual Car object". This is also refered to as "instantiation". The Car class requires you to specify a color when instantiating it which is defined by its constructor and the constructor sets the Car's color to red. Research what a "class constructor" is - I will go into this later because I see one of your question marks on it below.
    Basically this statement is creating a red Car - not setting a Car's color to be red.

    [b]// declaring it green[/b]
    - Same thing here - you are creating a new green Car - not setting an existing Car's color to green. Here you are saying "Overwrite the previously created 'red Car' with a new 'green Car'".
    Now because you are working in the .Net framework - the red car is actually still in memory somewhere and will automatically be disposed of at some point - but the variable named 'car' is now pointing at the green Car instead of the red Car. .NET is what is called a "Managed Environment" - Research "Managed Memory" and "Garbage Collection".

    [b]//allows user to c writeline[/b]
    - Uhm... So "Console" is a class just like "Car". Console has a method called ReadLine() which will allow a user to type in a bunch of letters - and when the user hits the enter key, it will return all the letters that were typed. This stops program execution until the user finishes typing. You can actually get what the user typed by changing the statement to something like this:
    [italic]string userInput = Console.ReadLine();[/italic]
    The variable 'userInput' will now hold what the user typed - you could even use that input to creat a new car like so:
    car = new Car(userInput);

    Just as a note - the closing brackets after the ReadLine statement are actually the end of your program. The 'class' statement on down could even be put in a different file because it is just the definition of a class and has nothing to do with the actual execution of your program.

    [b]//settin up a private variable of type string[/b]
    - Yes, color is part of the Car's internal, unviewable memory.

    [b]// a method?[/b]
    - This is a constructor. It IS a method - but a special method that is used to 'instantiate' your class. By default, any class can be created with a default constructor that has no parameters. So for example if you did not put this constructor you would simply use the following statement to create a new car:
    [italic]car = new Car();[/italic]
    and you would then have to specify the color manually by setting the "Color" property - (research "class Properties") like so:
    [italic]car.Color = "Red";[/italic]
    When you make a statement like "new Car("red")" you are telling C# to look for a method named "Car" in a class named "Car" that has one 'string' parameter. It will then find a matching constructor definition in your Car class. The way you can tell that a method is indeed a constructor is #1 it will be the same name as the class it is in and #2 it will have no return type specified - because its name IS the return type.

    [b]this.color = color; //?[/b]
    - So this is where things can get tricky in your head...
    Remember that any code you write in a class can be a part of any number of different objects. The class definition should not be thought of as an object, but rather a blue-print for an object. You could actually have 3 different Cars in your program and each of them will have a different color. So if you were to ask the blue Car what the private 'color' variable had in it, it would say it holds the value "blue". But if you asked the red Car the same question, it would say the value "red". This is because for each 'instantiated' car, the 'color' variable refers to a different spot in your program's memory. - so inside your Constructor method, you are saying that for 'this' instance of the 'Car' class, set the 'color' variable to the specified value. 'this' is a keyword you can use in the code of a class that refers to the actual instance of the class that is executing that code.
    - Now it just so happens that the person who wrote this code also named the 'parameter' in your 'constructor' the same name as the private variable in your class - this is a bad practice because it is confusing. Typically if you have a 'private' variable in your class you would preceed its name with an underscore. So in this case your private variable would be named _color instead of color. This way you can tell the difference between it and a parameter passed to a method or constructor.

    So the simple explanation to this is when this Car class is being instantiated, you are requiring a 'color' to be set and you are setting the private 'color' variable to that value. See also "Class Instance Variables"

    [b]// describe method?[/b]
    - Yes, this is the code that will be executed when you write a statement like so:

    [b]return "This car is " + Color; //?[/b]
    - This is the actual code that is inside the 'Describe' method. As you can see in the definition of the 'Describe' method that this method is expected to return a 'string'. The 'return' keyword means that you are sending a value back to whatever code called the 'Describe' method. In here you are taking a hard-coded string "This car is " and concatenating the string held in the 'Color' property. Then returning that assembled string to the calling code.
    The calling code, then takes that value and puts it on the screen using the Console.WriteLine() method. (you are passing that value into the parameter area of the WriteLine() method.

    [b]// is this where the colour is set?[/b]
    - Kinda, This is what is called a "Property". This entire statement:
    public string Color
    get { return color; }
    set { color = value; }
    Will define code for "getting" and "setting" the value of this property. Think of this like a variable that is attached to an instance of the Car class - except instead of just referencing a value stored in memory - you actually define what happens when some code is retrieving and assigning its value.
    So when you say Console.WriteLine(car.Color), the code in the 'get{ }' block will be executed and will expect you to ultimately return a string that the WriteLine method can use.
    When you say car.Color = "Red", the code in the 'set { }' block will be executed and the 'value' keyword will hold the value "Red" (in this case).

    What you see here is a standard property definition that just exposes an underlying private member - in your case this property is just revealing the private variable 'color' to the outside world. Since the private variable 'color' can't be accessed by outside code (you can't say car.color), you have to access the 'Color' property (so car.Color).

    You could have simply exposed the 'color' variable as public instead of private and the outside world would have been able to read and write to it - but this is not considered a wonder full practice because it would require a much larger code change if you ever had to alter how the input/output of color was being handled than you would by using a property exposure.

    For example, let's say later a new requirement is added that your class would need to make sure that color is never set to 'null'. Using the 'set{}' block you could put in code that made sure that if 'value' was null, that you would instead set 'color' to an empty string ("" or string.empty).
    this.color = value ?? ""; // this means set color to value, unless it's null - otherwise set it to ""
  • Hi, thanks again for the reply, ive spent a few hours going over it n trying to pose some new questions on the parts im not 100% sure of.

    Q1, Metadata = All information used by the CLR (Common Language Runtime) to describe and reference types and assemblies. (all definitions are from

    It mentions Types, does this include type members or just types?

    Q2, Assembly Manifest = Detailed description of the assembly contents. A manifest contains metadata describing the name, resources, types and version of the assembly as well as dependencies upon other assemblies.

    Does this mean that assemblies are like a table of contents detailing how your different assemblies interact with eachother? If so am i correct in assuming that a single file manifest is just a grouping of metadata n doesnt actually contain any info on how assemblies interact?

    Q3,"This.color = colour; //?"

    If you have multiple objects in the same class with the same name, how does the programme distinguish between each of the objects? (is this similar to method overloading?)

    Q4, // declaring it green
    - Same thing here - you are creating a new green Car - not setting an existing Car's color to green. Here you are saying "Overwrite the previously created 'red Car' with a new 'green Car'".
    Now because you are working in the .Net framework - the red car is actually still in memory somewhere and will automatically be disposed of at some point - but the variable named 'car' is now pointing at the green Car instead of the red Car. .NET is what is called a "Managed Environment" - Research "Managed Memory" and "Garbage Collection".

    GC is the process whereby the Common Language Runtime (CLR) reclaims memory that is no longer in use
  • Q1: If you are just learning about C# then metadata isn't something you really really need to worry about at all - your compiler will 100% take care of managing all of this. However - all metadata refers to in .net is just a cache that the CLR uses to reference classes and their methods, parameters, and attributes. It describes both the classes that are inside your program and all of the classes that your classes reference. Yes, this includes information about their members.

    Q2 : I'm not sure what you mean by "interact" but all this handles is mapping out all the files of an assembly, and handles resolution of types and resources for that assembly - I don't believe it has much to do with handling multiple assemblies -
    Again, this is something you could live the rest of your life not knowing about.

    Q3 : ok, so do some more research on exactly what a Class is and an instance of a class. Also look up what "Scope" is and how it relates to class (instance) variables.
    Take the following class for example:
    public class MyClass
    private string myVariable;

    public void SetInternalVariable(string value)
    myVariable = value;

    public string PrintTwoStrings(string myVariable)
    Now let's put this into a quick program...
    MyClass myInstance1 = new MyClass();
    MyClass myInstance2 = new MyClass();

    myInstance1.SetInternalVariable("I'm inside instance 1");
    myInstance2.SetInternalVariable("I'm inside instance 2");

    myInstance1.PrintTwoStrings("Printing instance 1:");
    myInstance2.PrintTwoStrings("Printing instance 2:");

    Now - both myInstance1 and myInstance2 return different results when calling the PrintTwoStrings method. Think an instance (or object) as a copy of a class in memory. Then think of each class as having a built in special variable called 'this'. The 'this' variable references the instance - or copy - that is currently executing your code.

    In some cases you actually have two variables with the same exact name and are only seperated by having different 'scopes'. For example in the method PrintTwoStrings - you have the string variable that was passed to the method named "myVariable" (this is a local scope) - and the private variable declared in your class also named "myVariable" (this is called an instance variable - it has a global scope in your class). If you need to work with the local variable named "myVariable" you simply just type out the name of the variable and C# assumes you mean the most-local variable of that name. Otherwise if you want to reference the variable that is actually attached to the calling instance of your class, you have to use the 'this' keyword. So:

    Sorry - it's really hard to understand this concept until you understand classes and instances better.

    Q4 : You are correct - I used poor terminology when describing that. No, you do not overwrite the red car - you merely tell 'car' to point to a different Car object. In a non-managed language you would actually be overwriting the memory that held the previous object.
    Managed memory has a ton of code behind the code you are actually writing. For example, when you create a new object in memory - your framework is actually handling all references to that object and keeping track of everything that is referencing that object at all times. During a periodic GC, if your framework sees that no one is referencing an object anymore - it marks that memory back to unreserved. The next time an object needs to be created - that memory can then be used to store its information.

    My suggestion is to really focus on Object Oriented Theory and Design. It seems you have a plenty solid understanding of the concept of "Programming" but are struggling with what "Object Oriented" programming is.

    Once you get a good grasp on OOP - things in C# will start to make a lot more sense - Also pick up a book on "Design Patterns" - this will help you understand object oriented programming more than anything.

    Think of C# as more of a tool to create Object Oriented Code (instead of a tool to create programs):
    If you think of it this way then no matter how much you know about C# - if you don't understand what you are trying to make with it then you'll never get anywhere.

  • Hi,
    Sorry for my late reply, i didnt actually get an email saying you had replied. Anyway thanks again for taking the time to answer my questions.

    regarding the following questions:

    (1) lol no worries i think i will give the whole topic a miss atm and try and focus on the general aspects of the programming language rather than try n get bogged down on its inner workings. its useful to touch on though so i may come back to it once i have gain a little more experience.

    (2) thanks for clearing that up :)

    (3) Ive done a little more reading as u suggested and i think the light bulb has just turned on. Quite chuffed thats cleared up, Thanks again :)

    (4) can you suggest any books that you believe may be helpful to object orientated programming and design patterns.

    i found the following book on design patterns on amazon after searching around n the reviews seem to be reasonable + it looks as it may meet my requirements.

    ive also started watching the programming methodology lectures from Stanford uni which are available on youtube as they talk about best practices etc + i figured since java was supposidly quite similar to c# that anything i picked up from them should easily be transfered to c#
  • Hi - this is psightoplazm, my account can't be logged into anymore for some reason...

    Anyways, yes - C# actually evolved from java - so conversion between the 2 is very easy.

    That being said - I would recomend the "Head First" book on design patters.
  • i had a feeling something was up as i tried to view ur profile yesterday n couldnt access it.

    Thanks for the book suggestion ill check it out

    + have a nice wknd :D
  • Hi
    i have finally managed to nail down one concept that im having problems with.... why do we need objects?

    i understand some ppl may be laughing at me for asking this question but its something im genuinely confused with so id appreciate some clarification.

    a class is an template which contains ur behaviours (methods) and data.

    a object is an instance of a class.

    but is it possible to have a program without an object? or do you always need an object of a class to be able to use the methods and data associated with that class? if so, how come there are programes which dont seem to have constructors?

    eg i dont believe the below code contains a constructor of the "HelloWorld" class

    using System;

    namespace MyHelloWorldApplication
    class HelloWorld
    static void Main(string[] args)
    Console.WriteLine("Hello World");

    i hope i have sufficiently explained my question

    thanks again for your time


  • I doubt anyone is laughing at you because EVERYONE goes through the same issues when being introduced with object oriented programming. I had to go through it and now it's your turn. To be completely honest, the answer will only come to you through time and practice. The reason I recomended reading up on design patterns and practices is because those books will make a huuuuuge impact on your understanding why OO design is so important.

    The answer to your question "can you program without objects" is yes. You can even get a language that doesn't rely on objects at all and just start coding away. Unless you are writing more than 100 lines of code you will probably never even care about object oriented programming.

    .NET is an OO framework that by design creates assemblies that contain classes. There is really no difference between an executable program and a code library (.dll) except that there is an "entry point" for the executable program. Because of the way .NET and assemblies are structured, one of the methods on one of the classes that are contained in an assembly are used as an "entry point" and this is where your program starts.

    Now, when you see a class without a constructor - that doesn't mean it doesn't have a constructor. That just means that .NET is smart enough to know that if you didn't specify a constructor in your code, to just put a default one in for you.

    There is just no reason to write out
    public MyClass()

    almost every time you make some tiny class.

    There are plenty of non OO languages still out there. Singleton languages that just simply read code from start to finish. They allow you to jump up and down a little bit - but for the most part you just have one big massive jumble of code.
    AND I'm willing to bet all of the hello world and other tiny projects that books will give you shed no light on why you would ever need anything else.

    The absolute biggest advantages to OOP, and you will only realize this over time, is Code Reusability and Maintainability.

    When you build a class - that class has a sole purpose and functionality. It doesn't care what program you stick it in, nor does it care about how many times you use it. And - when you are using a class in your code - you don't care HOW it does what is does - you just care that it only takes you one or two line of code (hopefully) to get your result. Aaaand when something goes wrong with that class - you don't have to debug your whole program and change your code in 7093 different places - you just go into your class and fix it. Since you hopefully used good OO practices - your class isn't depenant on the rest of your program so it is the ONLY place you have to make a fix to.

    When you use singleton languages your code is 100% entangled in itself. You absolutely WILL have to copy and paste the same exact code many, many, many times over again. Making a change to one thing means you have to go back over all of your code and refactor it in many, many, many places. Making a change or a fix means you also have to remember every place you pasted that same code to and fix it there also. Program flow becomes completely unreadable (when you start jumping aroudn alot) and you will come back to your same code only a couple weeks to a month later and honestly have no idea what the hell you were doing.

    Besides this OO just helps you think better. You won't run into any of these issues until you start trying to make larger projects.

    Here is some non-OO thinking:
    "I need to stick that here in this part of my loop. I need to make sure this variable has already been set/declared so that block will work here, here, and here: And for this other result I need to call this external web source (which requires setting up the communication driver - which is technically an object btw) and then run it through this equation before parsing the result into a binary format so that I can store it in this memory. Then I have to do a file operation which will include checking if the file is there, if so-delete it, then create a new file, oh - and make sure I have access to do all this so I don't crash, then I have to set the file buffer length to the number of bytes that I need to write - and oh ya, I don't have that value yet, so I need to go back up in the code and do this calculation..."

    With OO you start thinking like this:
    "I am writing a workflow - I need serviceA, serviceB and serviceC, and I will need helperObjectA:
    Now get the result from serviceA, serviceB, and serviceC, and process it with helperObjectA - ok, done"

    Even in my example it was almost impossible to keep away from objects. Tecnically a file is an object - so a truly non-object oriented design would have to peek and poke into memory, access the drive's functionality through various memory location, read and write data to it manually - know how the disk is formatted, know how to find a file's header data, now how to find empty blocks and reserve disk space for your file.

    Yes, that seems like I'm being extreem - but this is directly out of the programming history books. If you ever want to have a really good time, buy an old apple IIe off of ebay or something - and look up the old assembly language it used to use - Hit open-apple, control, escape (or something like that - why do I remember this...) and start writing in hexadecimal. No joke, if you want to access the disk drive - you are basically working the comptuer through it's different memory locations.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!