Jump to content

  • Log In with Google      Sign In   
  • Create Account

Awesome job so far everyone! Please give us your feedback on how our article efforts are going. We still need more finished articles for our May contest theme: Remake the Classics

- - - - -

C# Workshop - Week 1 (Ch. 1 & 2) - Advanced

  • You cannot reply to this topic
338 replies to this topic

#1 JWalsh   Moderators   -  Reputation: 422

Like
0Likes
Like

Posted 30 June 2007 - 06:15 PM

Welcome to the GDNet C# Workshop – Ch. 1 & 2

For a complete introduction to this workshop, please look here. Workshop Overview This workshop is designed to aid people in their journey to learn beginning C# (C-Sharp). This workshop is targeted at highly motivated individuals who are interested in learning C# or who have attempted to learn C# in the past, but found that without sufficient support and mentoring they were unable to connect all the pieces of this highly complex but powerful programming language. This is a 'guided' self-teaching C# workshop. Each student is responsible for taking the time to read the material and learn the information. Additionally, this workshop does not attempt to defend C# as a language, nor does it attempt to demonstrate that C# is either more or less useful then other programming languages for any particular purpose. People who intend to start a discussion about the differences between C# and ANY other languages (except as are relevant to a particular discussion), are encouraged to do so elsewhere. This workshop is for educational, not philosophical discussions. Finally, the community and tutors that arise out of this workshop are here for making the learning process run more smoothly, but are not obligated to baby-sit a person's progress. Because everyone will be working from the same references (.NET Book Zero and optionally the C# Language Specification 1.2 & 2.0), students may find it easier to get answers to the specific questions they might have. There is no minimum age requirement, and there is no previous programming experience required. However, we will be moving quickly so it's essential that students stay on task and dont fall behind. Experienced C# Programmers Feel free to post your own additional knowledge about the topics, however please try and keep the information you provide objective. If you MUST provide subjective/opinion-based information, please do so by marking the paragraph with [opinion] tags. This will make it clear to the readers what is fact, and what is opinion. Also, it may be relevant to mark some information with [observation] tags for information which you’ve “observed” but may not be fact. Finally, if you’re providing information which is related to common programming errors, you might tag it with a [warning] tag. Also, feel free to post links to additional resources about the topics for this week. I will do my best to add those to the “Additional Resources” section at the bottom of this post. Quizzes & Exercises Each week I will post review questions and exercises in the weekly thread. Please try and answer them by yourself. Once you've done so, feel free to look over the answers provided by others and submit your own answers if you've not yet seen them posted yet. Discussion about the quiz questions and answers is encouraged for clarification. Finally, experienced C# programmers may feel free to post quiz-like questions and exercises of their own.

Chapters 1 & 2 – Introduction & Lexical Structure

Introduction Greetings everyone and welcome to the C# Workshop. This week we begin the workshop with what I effectionately call the "Everything and The Kitchen Sink" chapters. You see, books on programming languages often try and cover tiny bits of information at a time, only showing you the information on a "need to know" basis. However, the majority of programming languages aren't implemented in bite-size chunks. They're complicated, intertwined devices necessarily complex for the purpose of doing complex things. Think about it...would it make much sense to teach English only by teaching the verbs first? "Dont worry, son, these verbs will all make sense when we've learned nouns in a few years." No. It would be frustrating as you wouldn't be able to put the verbs in context. As people who've previously read programming books can testify to, when the information is presented in bite-sized chunks, keeping relevant information from you until later, it's often common to answer questions with yet MORE questions. As well, you often find yourself saying "ooooh, so that's how this is used, I wish I'd known that 5 chapters ago when they first introduced it." With that being said, the C# specification takes a different approach. They give you a complete overview of the entire language, from concept to implementation...in the first chapter. Is this overwhelming? Hell yes. I'll be honest with you, after reading the first two chapters you wont be able to write much more than a "Hello World" program. You're not going to know much about the syntax, however, you'll have received an invaluable survey of the language. As we come upon later chapters where the information in chapter 1 is presented in more depth, the terminology will have more meaning to you after having received this overview. So in spite of the fact that you're likely to read these first two chapters and go uhhh....I dont get it, I encourage you not to give up. The purpose of the first two chapters isn't really to teach you the language, but instead to get you comfortable with the elements that make up the language. It's basically the teacher saying..."Well, this isnt going to teach you English, but...English is made up of Nouns, Verbs, Adjectives, etc..." Outline of the Reading - Chapters 1 & 2
  1. Hello World
  2. Program Structure
  3. Types and Variables
  4. Expressions
  5. Statements
  6. Classes and Objects
  7. Structs
  8. Arrays
  9. Interfaces
  10. Enums
  11. Delegates
  12. Attributes
  1. Programs
  2. Grammars
  3. Lexical Analysis
  4. Tokens
  5. Pre-Processing Directives
Additional Resources A good general overview of C# is located at the following URL, with decent descriptions and plenty of code samples. I highly encourage all complete programming beginners to check it out. http://www.publicjoe.f9.co.uk/csharp1/csharp03.html

Good Luck!

[Edited by - JWalsh on July 21, 2007 10:30:37 PM]
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints

Ad:

#2 JWalsh   Moderators   -  Reputation: 422

Like
0Likes
Like

Posted 30 June 2007 - 06:15 PM

Chapter 1 & 2 Review Questions

Greetings everyone. Since it's Friday I wanted to take a moment to provide to you the answers I had when writing the review questions for this week. Please look over the following answers and make sure it matches with yours. If it doesn't and you're confused about why not, please post your questions here or in in the advanced thread for Week 1.

  1. What is component-oriented programming?
    Contemporary software design increasingly relies on software components in the form of self-contained and self-describing packages of functionality

  2. What are the keys to software components in C#?
    Key to such components is that they present a programming model with properties, methods, and events; they have attributes that provide declarative information about the component; and they incorporate their own documentation

  3. What is Garbage Collection?
    Garbage collection automatically reclaims memory occupied by unused objects;

  4. What is exception Handling?
    exception handling provides a structured and extensible approach to error detection and recovery;

  5. What benefits do type safety provide you in C#?
    design of the language makes it impossible to have uninitialized variables, to index arrays beyond their bounds, or to perform unchecked type casts.

  6. What is a unified type system?
    All C# types, including primitive types such as int and double, inherit from a single root object type.

  7. What are the benefits of a unified type system?
    all types share a set of common operations, and values of any type can be stored, transported, and operated upon in a consistent manner.

  8. What's the purpose of namespaces?
    Namespaces provide a hierarchical means of organizing C# programs and libraries.

  9. What directive allows unqualified use of the members of a namespace?
    The 'using' directive.

  10. What is the entry point of a C# Console application?
    A static method named "main."

  11. What's the name of the C# Runtime libraries?
    The .NET Framework Library

  12. What are the key organizational concepts in C#?
    Programs, namespaces, types, members, and assemblies.

  13. What two things do C# assemblies contain and what form are they in?
    Executable code in the form of Intermediate Language and symbolic information in the form of metadata

  14. What happens to the IL instructions just before the code is executed?
    It is converted into processor-specific code by the JIT compiler of the .NET CLR.

  15. When are forward decelerations needed in C#?
    Never.

  16. What are the two kinds of variable types in C# what's the difference?
    Valye types and reference types. Value types store data directly, reference types store references to their data.

  17. How are C#'s value types subdivided?
    simple types, enum types, and struct types.

  18. How are C#'s reference types subdivided?
    Class types, interface types, array types, and delegate types.

  19. What is the encoding of a C# character, and how much memory does a single character require?
    Unicode encoding. It requires 16-bits.

    ####
  20. What are the sizes of each of the Simple Types, and their range of values?

  21. Which 5 categories of C# types are user-definable types?
    class, struct, interface, enum, and delegate.

  22. Give an overview of each of the 5 types.
    A class type defines a data structure that contains data members (fields) and function members (methods, properties, and others). Class types support inheritance and polymorphism, mechanisms whereby derived classes can extend and specialize base classes.

    A struct type is similar to a class type in that it represents a structure with data members and function members. However, unlike classes, structs are value types and do not require heap allocation. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.

    An interface type defines a contract as a named set of function members. A class or struct that implements an interface must provide implementations of the interface’s function members. An interface may inherit from multiple base interfaces, and a class or struct may implement multiple interfaces.

    An enum type is a distinct type with named constants. Every enum type has an underlying type, which must be one of the eight integral types. The set of values of an enum type is the same as the set of values of the underlying type.

    A delegate type represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. Delegates are similar to the concept of function pointers found in some other languages, but unlike function pointers, delegates are object-oriented and type-safe.
  23. What is "boxing" and "unboxing"
    The process of casting a C# value type to an object.

  24. What are expressions?
    Expressions are constructed from operands and operators

  25. What is the relationship between operators and operands in an expression?
    Operators tell what operation to perform on the operands.

  26. What is an operator's precedence?
    A rule which governs the order in which the operator is evaluated relative to other operators.

  27. What is operator overloading?
    Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type.

  28. What are the different kinds of C# statements, and what do they do??
    Blocks - Allows multiple other statements in place of a single statements
    Decelerations - declare variables and constants
    Expressions - Evaluate an expression.
    Selection - Also called branching, changes the flow of execution
    Iteration - Similar to branching, allows execution of the same code repeatedly with some variance
    Jump - Similar to branching, changes the scope of execution
    Try...catch - Used to catch exceptions
    Checked/unchecked - Used for checking underflow and overflow in integral types
    Lock - Use for mutually exclusive locks of data for thread safety
    using - use to temporarily obtain resources and dispose of them.

  29. What is a class?
    A class is a data structure that combines state (fields) and actions (methods and other function members) in a single unit.

  30. Create an example class named Character. Dont worry about members, methods, or properties
    public class Character
    {

    }

  31. What operator is used to create a new instance of a class? What's the syntax to create a Character object?
    The new operator
    Character myCharacter = new Character();

  32. What are the different types of members of a class?

    Constants - The constant values associated with the class
    Fields - The variables of the class
    Methods - The computations and actions that can be performed by the class
    Properties - The actions associated with reading and writing named properties of the class
    Indexers - The actions associated with indexing instances of the class like an array
    Events - The notifications that can be generated by the class
    Operators - The conversions and expression operators supported by the class
    Constructors - The actions required to initialize instances of the class or the class itself
    Destructors - The actions to perform before instances of the class are permanently discarded
    Types - The nested types declared by the class

  33. What are the 5 types of Accessibility used on a class's members?

    public - Access not limited
    protected - Access limited to this class and classes derived from this class
    internal - Access limited to this program
    protected internal -Access limited to this program and classes derived from this class
    private Access limited to this class

  34. What does inheritance mean?
    Inheritance means that a class implicitly contains all members of its base class, except for the constructors of the base class

  35. What is a field?
    A field is a variable that is associated with a class or with an instance of a class.

  36. What is the difference between a static and non-static field?
    A static field has exactly one memory storage location, which is shared by all instances of a class. non-static is a unique
    memory address for each instance.

  37. What is a method of a class?
    A method is a member that implements a computation or action that can be performed by an object or class.

  38. What's the difference between static and non-static methods?
    Static methods are accessible from the class, while non-static are accessible from the instances of the class, or "objects."

  39. What are parameters?
    list of arguments, which represent values or variable references passed to the method

  40. What are return types?
    specifies the type of the value computed and returned by the method

  41. What does a signature of a method consist of?
    The signature of a method consists of the name of the method and the number, modifiers, and types of its parameters. The signature of a method does NOT include the return type.

  42. What are the 4 types of parameters and how are they used?
    Value, reference, output, and arrays. Value is for input parameters. Reference parameters are used for both input and output. Output parameters are used simply for outgoing parameter passing. Parameter arrays allow a variable number of arguments to be passed into the method.

  43. What is a static method?
    A method declared with a static modifier. It does not operaote on a specific instance of a class, and can only access static members.

  44. What is an instance method?
    Any method created without the static modifier. It operates on specific instance of the class, and can access both static and non-static members.

  45. What's the difference between a virtual and non-virtual method?
    When a virtual method is invoked, it's runtime type for the instance is invoked. For a non-virtual method, the compile-time type is invoked.

  46. What does it mean to override a virtual method?
    The method overrides an inherited virtual method with the same signature, thus providing a new implementation for that method.

  47. What is an abstract method and when is it permitted?
    A method with no implementation. It is only permitted in classes also declared abstract.

  48. What is method overloading?
    Method overloading permits multiple methods in the same class to have the same name, so long as they have unique signatures.

  49. What is the difference between an instance constructor and a static constructor?
    Instance constructors are called when an object is created, to initialize the object. Static constructors are called by the CLR when a class is loaded, and is used to initialize the class itself.

  50. What is the primary difference between properties and fields?
    Properties do not denote storage locations, and instead provide accessors which specify the statements to be executed when their values are read or written to.

  51. How do you make a property read-only?
    Dont provide a set method.

  52. What is an indexer?
    An indexer is a member that enables object to be indexed in the same way as an array. It is declared like a property, except the name is always "this" followed by a parameter list written between square brackets.

  53. What is an event, and what is true of it's type?
    An event is a member that enables a class or object to provide notifications. The type must always be a delegate.

  54. What are event handlers?
    Event handlers are methods attached to an event using the += operator and removed with the -= operator.

  55. What is a class operator?
    Its a member that defines (re-defines) the meaning of applying a particular expression operator to instances of the class.

  56. What is a destructor?
    A member that implements the actions required to destruct an instance of a class - specifically non-garbage collected member data.

  57. What's the main difference between classes and structs?
    Structs are value types instead of the reference types, and can be created on the stack, rather than the heap. A struct directly stores the data of the struct, while a class stores a reference to an object. Also, structs do not support inheritance.

  58. What is an array?
    An array is a data structure that contains a number of variables of the same type that are accessed through computed indices.

  59. What is an array initializer?
    A way of initializing the values within an array during construction of the array.

  60. What is an interface, and what can it contain?
    An interface defines a contract that can be implemented by classes and structs. An interface can contain methods, properties, events, and indexers.

  61. What are enums?
    enums are a value type which contain a set of named, symbolic constants.

  62. What is an enum's underlying type?
    All enums have an underlying integral type. Those that are not specified have default underlying type of 'int'.

  63. What is a delegate?
    A delegate represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as variables which can be assigned and passed as parameters.

  64. What is the purpose of attributes?
    To allow user-defined types of declarative information that can be attached to program entities and retrieved at run-time.

  65. What is a compilation unit in C#?
    It's a source file

  66. What are the 3 steps in compiling a program?
    1. Transformation
    2. Lexical Analysis
    3. Syntatic Analysis

  67. What encoding are C# files in? ie. ASCII?
    Unicode

  68. What is the purpose of lexical grammar?
    It defines how Unicode characters are combined to form line terminators, white space, comments, tokens, and pre-processing directives.

  69. What is the purpose of syntactic grammar?
    Defines how the tokens resulting from the lexical grammar are combined to form C# programs.

  70. What is contained within the first line of a grammar rule?
    The non-terminal symbol being defined, followed by a colon.

  71. When you see the suffix "opt" in a grammar rule, what does it mean?
    It means the previous term is optional.

  72. What are the five basic elements that make up the structure of a C# source file?
    Line terminators, white space, comments, tokens, and pre-processing directives.

  73. Which of the 5 elements of a C# source file are relevant to the syntax of a C# file?
    The tokens.

  74. What do line terminators do?
    divide the characters of C# source files into lines.

  75. What are the two forms of comments supported by C#, give examples.
    Single line comments, which start with // and comment out everything else on the line...and...
    Delimited comments, which are anything between /* and */, even spanning multiple lines.

  76. What are the 5 types of tokens?
    Identifiers, Keywords, literals, operators, and punctuators.

  77. List ALL of the C# keywords

    abstract as base bool break
    byte case catch char checked
    class const continue decimal default
    delegate do double else enum
    event explicit extern false finally
    fixed float for foreach goto
    if implicit in int interface
    internal is lock long namespace
    new null object operator out
    override params private protected public
    readonly ref return sbyte sealed
    short sizeof stackalloc static string
    struct switch this throw true
    try typeof uint ulong unchecked
    unsafe ushort using virtual void
    volatile while

  78. What is a literal, and what are the 6 types of literals?
    A source code representation of an actual value.
    boolean
    integer
    real
    character
    string
    null

  79. Give an example of each type of literal.
    true
    200
    200.23
    'c'
    "Hello, World"
    null

  80. What is a verbatim literal string, and how is it created?
    A verbatim literal is one with a @ at the beginning, and in a verbatim string, escape characters are not interpreted.

  81. What are the possible Pre-processing directive, what is their function, and what is their intended use?
    #define, #undef - defining and undefing symbols
    #if, #elif, #else, #endif controling conditional compilation based on the existance of defined symbols
    #line changing the line number and file name of source.
    #error and #warning, used to generate compile-time warnings and errors
    #region and #endregion used to group lines of source code for a programmer.
Chapter 1 & 2 Exercises

As this week is largely an overview of the entire language and doesnt go into significant enough detail to warrant a large number of exercises, we'll keep it simple for this week. Next week, however...[wink]

1. Write a program which outputs your name to the console.

using System;
class Hello
{
static void Main()
{
Console.WriteLine("My name is Jeromy Walsh");
}
}




[Edited by - JWalsh on July 6, 2007 5:15:19 PM]
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints

#3 Rahl   Members   -  Reputation: 109

Like
0Likes
Like

Posted 30 June 2007 - 06:22 PM

Yay!

#4 ecttm   Members   -  Reputation: 122

Like
0Likes
Like

Posted 30 June 2007 - 07:12 PM

I am may asking stupid here,
but where is the stuff to read?

#5 Alpha_ProgDes   Crossbones+   -  Reputation: 3292

Like
0Likes
Like

Posted 30 June 2007 - 07:15 PM

First question. What's the difference between readonly and const? They seem to do the same thing.

Second question. A delegate is a first class property. And a function pointer (in C++) isn't? But can't you declare and pass function pointers around just like you can delegates? I guess I'm asking what's the real difference.

#6 JWalsh   Moderators   -  Reputation: 422

Like
0Likes
Like

Posted 30 June 2007 - 07:17 PM

Check the workshop overview here in this thread, or the introduction thread. In both places are the links to the 1.2 and 2.0 C# Specifications. As indicated in this thread, everyone's assignment for this week is chapters 1 and 2 of the 1.2 specification.

If you have any questions while you're reading, just pop into the forum and ask clarification questions. Also, use the review questions as a benchmark for whether or not you're catching the relevant information.

Cheers!
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints

#7 Washu   Senior Moderators   -  Reputation: 3113

Like
0Likes
Like

Posted 30 June 2007 - 07:22 PM

Quote:
Original post by Alpha_ProgDes
First question. What's the difference between readonly and const? They seem to do the same thing.

Readonly types are initialized in the constructor, this allows for complex initialization requirements to be met. Const types are initialized at decleration, allowing only the most basic of initialization capabilities. Furthermore, const types appear as static members of the class, while readonly types can be static or instance. Use const for compiletime constants, and readonly for runtime constants.
Quote:
Second question. A delegate is a first class property. And a function pointer (in C++) isn't? But can't you declare and pass function pointers around just like you can delegates? I guess I'm asking what's the real difference.
A delegate is similar to a function pointer, except slightly more complex (in that it can point to instance methods as well as static methods). Delegates can also be used to point to dynamic methods, something that will be covered later.

#8 JWalsh   Moderators   -  Reputation: 422

Like
0Likes
Like

Posted 30 June 2007 - 07:42 PM

Alpha_ProgDes,

To further elaborate on what Washu said, a C# delegate is object oriented, strongly typed, and is in fact an object of type System.Delegate. Whereas C++ function pointers are not.

As a result, there are methods you can invoke with a delegate object which you cannot with simple function addresses. We'll get into more details about the differences when we cover Delegates.

Cheers!


Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints

#9 hpjchobbes   Members   -  Reputation: 140

Like
0Likes
Like

Posted 30 June 2007 - 09:06 PM

Here's some questions I have after reading the first two chapters as well as trying to answer the review questions:

The IL instructions get converted to processor specific code by the JIT compiler. Is this code saved so it doesn't have to keep getting recompiled, and is it possible to pre-compile the code so the JIT doesn't have to when it is run? If so, what are the pros/cons of letting the JIT compile it at runtime?

What is the main difference between REF and OUT? It seems like they could be interchanged and the code would still operate the same.

When would a programmer need to use the LOCK statement in a program?

When dealing with a class that inherits from a base class, the document states: " Inheritance means that a class implicitly contains all members of its base class, except for the constructors of the base class". In the example, they show a Point3D class that inherits from a Point class. The Point3D's constructor inherits from the Point constructor. Does the inherited constructor ever get run? In the example, do X and Y not get values since the Point3D constructor didn't specify?

On a similar topic to class inheritance, what's the difference between inheriting a function vs. overriding the function? It would seem that if you inherit then the base function would still get called, but I'm not sure.

Last, I'm not sure I understand what "Metadata" is, other than the document states that it contains symbolic information. What does this mean?

I hope I didn't overload with two many questions but I want to make sure I have a good understanding and there's a lot of information in these first two chapters.

#10 SamLowry   Members   -  Reputation: 1206

Like
0Likes
Like

Posted 30 June 2007 - 09:36 PM

Quote:
Original post by hpjchobbes
What is the main difference between REF and OUT? It seems like they could be interchanged and the code would still operate the same.


It's all about preventing the programmer from reading unitialized variables's values:

int x;
x += 2; // error, as x is not guaranteed to have been initialized to 0

From the specification (1.6.5.1):
Quote:

A reference parameter is used for both input and output parameter passing

Quote:

An output parameter is used for output parameter passing.

The compiler performs different checks: when passing a variable as ref, it must have been initialized before the method call. This is not the case for out arguments.


// Please do not write code like this
// It's only an example
void SquareOut(int x, out int y)
{
y = x * x;
}

void SquareRef(int x, ref int y)
{
y = x * x;
}

void Func1()
{
int result; // uninitialized
SquareOut(2, out result); // will work
}

void Func2()
{
int result; // uninitialized
SquareRef(2, ref result); // won't work
}



Func2 contains an invalid call to SquareRef: as ref arguments can be used for input also, this means it might be that SquareRef attempts to read result's value, but in our case it would not have been initialized yet. The C# compiler prevents such things from happening. You can make the compiler happy again by changing SquareRef's first line to int result = 0;.

The compiler will perform the same checks on SquareOut: as out arguments are only meant for output, they're not guaranteed to have been initialized. Hence, SquareOut is not allowed to read result's value before having assigned it a value itself:


void SomeFuncWithOut(out int x)
{
Console.WriteLine( x ); // error
x = 1;
Console.WriteLine( x ); // ok
}


In summary, the rules are

  1. A local variable is initially uninitialized.

  2. Reading an uninitialized variable is an error.

  3. Assignment initializes a variable.

  4. An incoming ref variable is assumed to be initialized.

  5. An incoming out variable is assumed to be uninitialized.

  6. It is forbidden to pass an uninialized variable using ref.


In the end, it's about making explicit how arguments are going to be used: some are simple inputs (default), some are to be used as outputs (out), and some as both (ref).

[Edited by - SamLowry on July 1, 2007 4:36:08 AM]

#11 SamLowry   Members   -  Reputation: 1206

Like
0Likes
Like

Posted 30 June 2007 - 09:56 PM

Quote:
Original post by hpjchobbes
When would a programmer need to use the LOCK statement in a program?

Short answer: synchronisation.

Longer answer: When (s)he's using multithreading and needs to make sure the shared state is handled correctly.

Answer in the context of "workshop's first week": I don't know your experience with these topics, so I'm just going to say "Don't worry about it now, you're not going to have to use it yet. When you do, you'll know."

#12 SamLowry   Members   -  Reputation: 1206

Like
0Likes
Like

Posted 30 June 2007 - 10:02 PM

Quote:
Original post by hpjchobbes

When dealing with a class that inherits from a base class, the document states: " Inheritance means that a class implicitly contains all members of its base class, except for the constructors of the base class". In the example, they show a Point3D class that inherits from a Point class. The Point3D's constructor inherits from the Point constructor. Does the inherited constructor ever get run? In the example, do X and Y not get values since the Point3D constructor didn't specify?

Think of a class hierarchy (A, B inherits from A, C inherits from B) as a tower. A would be the lowest level, C the highest. When building such a tower, the levels must be built in order: first level A, then B, then C. Same thing happens with constructors. First, one of A's constructors must be called, then one of B's constructors, and lastly, one of C's.
So to answer your question: Point's constructor does get to run indeed, and it runs first.


public class Point3D: Point
{
public int z;
public Point3D(int x, int y, int z)
: Point(x, y) // <-----
{
this.z = z;
}
}

The arrow points to the code which shows which of the base's constructors (there can be more than one due to overloading) needs to be called with what arguments. If that line were omitted, it would be interpreted as an implicit call to the default constructor (which structs always have, classes not necessarily).

Paragraph 10.10.1 in the spec explains fully how constructors are called.
As an example:


class A
{
A() { ... }
A(int x) { ... }
A(string s) { ... }
}

class B : A
{
B() { ... } // construction order: A(), B()
B(int x) : base(x.ToString()) { ... } // order: A(string), B(int)
}

class C : B
{
C() : base(5) { ... } // order : A(string), B(int), C()
C(string s) { ... } // order : A(), B(), C(string)
}







What it means for constructors not to be inherited (using the spec's Point example):
Point provides two constructors:
  • one implicit default constructor taking 0 arguments and initializing x and y to 0

  • one taking 2 integer arguments


Point3D provides two constructors: one with 0 arguments (x, y, z = 0) and one with 3 int-arguments.

If constructors were to be inhereted, Point3D would have a third constructor: the one from Point taking 2 arguments. This is not the case.

[Edited by - SamLowry on July 1, 2007 4:02:33 AM]

#13 SamLowry   Members   -  Reputation: 1206

Like
0Likes
Like

Posted 30 June 2007 - 11:21 PM

Quote:
Original post by hpjchobbes
Last, I'm not sure I understand what "Metadata" is, other than the document states that it contains symbolic information. What does this mean?

Don't worry too much about it, it'll become clearer when we'll discuss attributes.


Metadata is "data about data". Consider MP3s: the data they contain is audio. The ID3 tags, containing information such as genre, lyrics, composer, album, rating, etc. gives extra information about the audio, hence ID3 can be called metadata.

Another example is the extra data the OS keeps about your files: creation date, last modification date, security settings, etc. all these are metadata.


From Wikipedia:
Quote:

.NET metadata, in the Microsoft .NET framework, refers to code that describes .NET CIL (Common Intermediate Language) code. A .NET language compiler will generate the metadata and store this in the assembly containing the CIL. Metadata describes all classes and class members that are defined in the assembly, and the classes and class members that the current assembly will call from another assembly. The metadata for a method contains the complete description of the method, including the class (and the assembly that contains the class), the return type and all of the method parameters. When the CLR executes CIL it will check to make sure that the metadata of the called method is the same as the metadata that is stored in the calling method. This ensures that a method can only be called with exactly the right number of parameters and exactly the right parameter types.


You can also add your own metadata using attributes (will be discussed later). There's much to be said about this topic, but again, as this is the first week... let's leave something for the 9 remaining weeks.

#14 SamLowry   Members   -  Reputation: 1206

Like
0Likes
Like

Posted 30 June 2007 - 11:34 PM

Quote:
Original post by hpjchobbes
On a similar topic to class inheritance, what's the difference between inheriting a function vs. overriding the function? It would seem that if you inherit then the base function would still get called, but I'm not sure.

I'm not sure about how to answer this one.

Quote:

When a type inherits from a base class, all members of the base class, except instance constructors, destructors and static constructors, become members of the derived type.

Inheriting means that all members (except for ...) of the base class are included in the subclass. Overriding means giving a new meaning to these members.


// Only relevant members are shown
class Rectangle
{
public float Width { get { ... } }
public float Height { get { ... } }

public virtual float Circumference
{
get { return Width * 2 + Height * 2; }
}

public virtual float Area
{
get { return Width * Height; }
}
}

// A square is a rectangle with Width == Height
class Square : Rectangle
{
public float Side { get { return Width; } }

public override float Circumference
{
get { return Side * 4; }
}
}

In this example, Square inherits both Circumference and Area but chooses to only override Circumference. This choice is completly arbitrary: I could have overridden both, or neither, the code will still generate the same results. Providing specialized versions in this case has a (small) impact on efficiency: more specialized algorithms can make more assumptions and hence use shortcuts to compute the result faster.

So, when computing the circumference of a Square, its own specialized version will be used. A Square's area will still be computed using Rectangle's logic.

#15 Petah   Members   -  Reputation: 122

Like
0Likes
Like

Posted 01 July 2007 - 02:26 AM

2: What are the keys to software components in C#?
- Programs, namespaces, types, members and assemblies.
- - "C# programs consist of one or more source files. Programs declare types, which contain members and can be organized into namespaces. When C# programs are compiled, they are physically packaged into assemblies."

11: What's the name of the C# Runtime libraries?
- .NET

48: What is method overloading?
- This is when one or more methods have the same name but are distinguished by the arguments and return type.

58: What is an array?
- It is a data structure that contains many variables accessed using an index.

#16 Ezbez   Members   -  Reputation: 1116

Like
0Likes
Like

Posted 01 July 2007 - 04:48 AM

I have a question when answering question 1. Is it correct to say that object-oriented programming is a type of component-oriented programming? It seems to me that OOP is a type of COP because OOP helps you create "self-contained and self-describing packages of functionality".

#17 finky45   Members   -  Reputation: 100

Like
0Likes
Like

Posted 01 July 2007 - 05:08 AM

Quote:
An implicit conversion exists from a class type to any of its base class types. Therefore, a variable of a class type can reference an instance of that class or an instance of any derived class. For example, given the previous class declarations, a variable of type Point can reference either a Point or a Point3D:
Point a = new Point(10, 20);
Point b = new Point3D(10, 20, 30);


Does this mean I can access the derived class' member functions if I cast it as a "Point"? i.e "b.setZ = 1337;"

#18 finky45   Members   -  Reputation: 100

Like
0Likes
Like

Posted 01 July 2007 - 05:23 AM

Quote:
Original post by Ezbez
I have a question when answering question 1. Is it correct to say that object-oriented programming is a type of component-oriented programming? It seems to me that OOP is a type of COP because OOP helps you create "self-contained and self-describing packages of functionality".


I don't understand the difference between the two. OOP does all the things that COP is described to do in the document. You can have components in OOP.

Quote:
C# is an object-oriented language, but C# further includes support for component-oriented programming. Contemporary software design increasingly relies on software components in the form of self-contained and self-describing packages of functionality. Key to such components is that they present a programming model with properties, methods, and events; they have attributes that provide declarative information about the component; and they incorporate their own documentation. C# provides language constructs to directly support these concepts, making C# a very natural language in which to create and use software components.


It seems to me it's just a lot of fancy talk for "we facilitated OOP a little more" but decided to give it a different name. Someone tell me why I'm wrong?

#19 TheTroll   Members   -  Reputation: 873

Like
0Likes
Like

Posted 01 July 2007 - 06:14 AM

Quote:
Original post by finky45

It seems to me it's just a lot of fancy talk for "we facilitated OOP a little more" but decided to give it a different name. Someone tell me why I'm wrong?


COP is more then just OOP with components. COP is a change in mindset much like OOP was a change from functional programming. In COP the interface is the center, like in OOP the object was the core. COP makes it so the design should support versoning and seperating the interface from the implimination. It brings the "black box" approach a little closer to reality.

theTroll



#20 SamLowry   Members   -  Reputation: 1206

Like
0Likes
Like

Posted 01 July 2007 - 06:20 AM

Quote:
Original post by finky45
Quote:
An implicit conversion exists from a class type to any of its base class types. Therefore, a variable of a class type can reference an instance of that class or an instance of any derived class. For example, given the previous class declarations, a variable of type Point can reference either a Point or a Point3D:
Point a = new Point(10, 20);
Point b = new Point3D(10, 20, 30);


Does this mean I can access the derived class' member functions if I cast it as a "Point"? i.e "b.setZ = 1337;"

No. The compile-time type determines which members you can access. In your case this type is Point, meaning access to Point3D-members is not allowed.





PARTNERS