Advertisement

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

Started by July 01, 2007 12:15 AM
337 comments, last by paulecoyote 17 years, 3 months ago

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
Chronicles of Elyria (An In-development MMORPG)
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
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?

  2. Contemporary software design increasingly relies on software components in the form of self-contained and self-describing packages of functionality

  3. What are the keys to software components in C#?

  4. 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

  5. What is Garbage Collection?

  6. Garbage collection automatically reclaims memory occupied by unused objects;

  7. What is exception Handling?

  8. exception handling provides a structured and extensible approach to error detection and recovery;

  9. What benefits do type safety provide you in C#?

  10. design of the language makes it impossible to have uninitialized variables, to index arrays beyond their bounds, or to perform unchecked type casts.

  11. What is a unified type system?

  12. All C# types, including primitive types such as int and double, inherit from a single root object type.

  13. What are the benefits of a unified type system?

  14. all types share a set of common operations, and values of any type can be stored, transported, and operated upon in a consistent manner.

  15. What's the purpose of namespaces?

  16. Namespaces provide a hierarchical means of organizing C# programs and libraries.

  17. What directive allows unqualified use of the members of a namespace?

  18. The 'using' directive.

  19. What is the entry point of a C# Console application?

  20. A static method named "main."

  21. What's the name of the C# Runtime libraries?

  22. The .NET Framework Library

  23. What are the key organizational concepts in C#?

  24. Programs, namespaces, types, members, and assemblies.

  25. What two things do C# assemblies contain and what form are they in?

  26. Executable code in the form of Intermediate Language and symbolic information in the form of metadata

  27. What happens to the IL instructions just before the code is executed?

  28. It is converted into processor-specific code by the JIT compiler of the .NET CLR.

  29. When are forward decelerations needed in C#?

  30. Never.

  31. What are the two kinds of variable types in C# what's the difference?

  32. Valye types and reference types. Value types store data directly, reference types store references to their data.

  33. How are C#'s value types subdivided?

  34. simple types, enum types, and struct types.

  35. How are C#'s reference types subdivided?

  36. Class types, interface types, array types, and delegate types.

  37. What is the encoding of a C# character, and how much memory does a single character require?

  38. Unicode encoding. It requires 16-bits.

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


  40. Which 5 categories of C# types are user-definable types?

  41. class, struct, interface, enum, and delegate.

  42. Give an overview of each of the 5 types.

  43. 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.
  44. What is "boxing" and "unboxing"

  45. The process of casting a C# value type to an object.

  46. What are expressions?

  47. Expressions are constructed from operands and operators

  48. What is the relationship between operators and operands in an expression?

  49. Operators tell what operation to perform on the operands.

  50. What is an operator's precedence?

  51. A rule which governs the order in which the operator is evaluated relative to other operators.

  52. What is operator overloading?

  53. 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.

  54. What are the different kinds of C# statements, and what do they do??

  55. 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.

  56. What is a class?

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

  58. Create an example class named Character. Dont worry about members, methods, or properties

  59. public class Character
    {

    }

  60. What operator is used to create a new instance of a class? What's the syntax to create a Character object?

  61. The new operator
    Character myCharacter = new Character();

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


  63. 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

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


  65. 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

  66. What does inheritance mean?

  67. Inheritance means that a class implicitly contains all members of its base class, except for the constructors of the base class

  68. What is a field?

  69. A field is a variable that is associated with a class or with an instance of a class.

  70. What is the difference between a static and non-static field?

  71. 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.

  72. What is a method of a class?

  73. A method is a member that implements a computation or action that can be performed by an object or class.

  74. What's the difference between static and non-static methods?

  75. Static methods are accessible from the class, while non-static are accessible from the instances of the class, or "objects."

  76. What are parameters?

  77. list of arguments, which represent values or variable references passed to the method

  78. What are return types?

  79. specifies the type of the value computed and returned by the method

  80. What does a signature of a method consist of?

  81. 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.

  82. What are the 4 types of parameters and how are they used?

  83. 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.

  84. What is a static method?

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

  86. What is an instance method?

  87. Any method created without the static modifier. It operates on specific instance of the class, and can access both static and non-static members.

  88. What's the difference between a virtual and non-virtual method?

  89. 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.

  90. What does it mean to override a virtual method?

  91. The method overrides an inherited virtual method with the same signature, thus providing a new implementation for that method.

  92. What is an abstract method and when is it permitted?

  93. A method with no implementation. It is only permitted in classes also declared abstract.

  94. What is method overloading?

  95. Method overloading permits multiple methods in the same class to have the same name, so long as they have unique signatures.

  96. What is the difference between an instance constructor and a static constructor?

  97. 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.

  98. What is the primary difference between properties and fields?

  99. 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.

  100. How do you make a property read-only?

  101. Dont provide a set method.

  102. What is an indexer?

  103. 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.

  104. What is an event, and what is true of it's type?

  105. An event is a member that enables a class or object to provide notifications. The type must always be a delegate.

  106. What are event handlers?

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

  108. What is a class operator?

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

  110. What is a destructor?

  111. A member that implements the actions required to destruct an instance of a class - specifically non-garbage collected member data.

  112. What's the main difference between classes and structs?

  113. 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.

  114. What is an array?

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

  116. What is an array initializer?

  117. A way of initializing the values within an array during construction of the array.

  118. What is an interface, and what can it contain?

  119. An interface defines a contract that can be implemented by classes and structs. An interface can contain methods, properties, events, and indexers.

  120. What are enums?

  121. enums are a value type which contain a set of named, symbolic constants.

  122. What is an enum's underlying type?

  123. All enums have an underlying integral type. Those that are not specified have default underlying type of 'int'.

  124. What is a delegate?

  125. 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.

  126. What is the purpose of attributes?

  127. To allow user-defined types of declarative information that can be attached to program entities and retrieved at run-time.

  128. What is a compilation unit in C#?

  129. It's a source file

  130. What are the 3 steps in compiling a program?

  131. 1. Transformation
    2. Lexical Analysis
    3. Syntatic Analysis

  132. What encoding are C# files in? ie. ASCII?

  133. Unicode

  134. What is the purpose of lexical grammar?

  135. It defines how Unicode characters are combined to form line terminators, white space, comments, tokens, and pre-processing directives.

  136. What is the purpose of syntactic grammar?

  137. Defines how the tokens resulting from the lexical grammar are combined to form C# programs.

  138. What is contained within the first line of a grammar rule?

  139. The non-terminal symbol being defined, followed by a colon.

  140. When you see the suffix "opt" in a grammar rule, what does it mean?

  141. It means the previous term is optional.

  142. What are the five basic elements that make up the structure of a C# source file?

  143. Line terminators, white space, comments, tokens, and pre-processing directives.

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

  145. The tokens.

  146. What do line terminators do?

  147. divide the characters of C# source files into lines.

  148. What are the two forms of comments supported by C#, give examples.

  149. 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.

  150. What are the 5 types of tokens?

  151. Identifiers, Keywords, literals, operators, and punctuators.

  152. List ALL of the C# keywords

  153. abstract	as		base		bool		breakbyte		case		catch		char		checkedclass		const		continue	decimal		defaultdelegate	do		double		else		enumevent		explicit	extern		false		finallyfixed		float		for		foreach		gotoif		implicit	in		int		interfaceinternal	is		lock		long		namespacenew		null		object		operator	outoverride	params		private		protected	publicreadonly	ref		return		sbyte		sealedshort		sizeof		stackalloc	static		stringstruct		switch		this		throw		truetry		typeof		uint		ulong		uncheckedunsafe		ushort		using		virtual		voidvolatile	while

  154. What is a literal, and what are the 6 types of literals?

  155. A source code representation of an actual value.
    boolean
    integer
    real
    character
    string
    null

  156. Give an example of each type of literal.

  157. true
    200
    200.23
    'c'
    "Hello, World"
    null

  158. What is a verbatim literal string, and how is it created?

  159. A verbatim literal is one with a @ at the beginning, and in a verbatim string, escape characters are not interpreted.

  160. What are the possible Pre-processing directive, what is their function, and what is their intended use?

  161. #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
Chronicles of Elyria (An In-development MMORPG)
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
Advertisement
Yay!
I am may asking stupid here,
but where is the stuff to read?
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.

Beginner in Game Development?  Read here. And read here.

 

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
Chronicles of Elyria (An In-development MMORPG)
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
Advertisement
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.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

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
Chronicles of Elyria (An In-development MMORPG)
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
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.
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 examplevoid 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]

This topic is closed to new replies.

Advertisement