Original Post
📌 Pinned
🔒 Locked
C# Workshop - Week 1 (Ch. 1 - 4) - Beginners
Advertisement
Chapter 1 & 2 Review Questions
Greetings everyone. Each week I will post review questions and exercises in the weekly thread. Please try and answer them by yourself; either as you're reading over the chapters, or afterwards if you prefer.
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. 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.
As this week is largely an overview of the entire language and doesnt go into significant enough detail to warrent 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.
Greetings everyone. Each week I will post review questions and exercises in the weekly thread. Please try and answer them by yourself; either as you're reading over the chapters, or afterwards if you prefer.
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. 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.
- What is component-oriented programming?
- What are the keys to software components in C#?
- What is Garbage Collection?
- What is exception Handling?
- What benefits do type safety provide you in C#?
- What is a unified type system?
- What are the benefits of a unified type system?
- What's the purpose of namespaces?
- What directive allows unqualified use of the members of a namespace?
- What is the entry point of a C# Console application?
- What's the name of the C# Runtime libraries?
- What are the key organizational concepts in C#?
- What two things do C# assemblies contain and what form are they in?
- What happens to the IL instructions just before the code is executed?
- When are forward declerations needed in C#?
- What are the two kinds of variable types in C# what's the difference?
- How are C#'s value types subdivided?
- How are C#'s reference types subdivided?
- What is the encoding of a C# character, and how much memory does a single character require?
- What are the sizes of each of the Simple Types, and their range of values?
- Which 5 categories of C# types are user-definable types?
- Give an overview of each of the 5 types.
- What is "boxing" and "unboxing"
- What are expressions?
- What is the relationship between operators and operands in an expression?
- What is an operator's precedence?
- What is operator overloading?
- What are the different kinds of C# statements, and what do they do??
- What is a class?
- Create an example class named Character. Dont worry about members, methods, or properties
- What operator is used to create a new instance of a class? What's the syntax to create a Character object?
- What are the different types of members of a class?
- What are the 5 types of Accessibility used on a class's members?
- What does inheritance mean?
- What is a field?
- What is the difference between a static and non-static field?
- What is a method of a class?
- What's the difference between static and non-static methods?
- What are parameters?
- What are return types?
- What does a signature of a method consist of?
- What are the 4 types of parameters and how are they used?
- What is a static method?
- What is an instance method?
- What's the difference between a virtual and non-virtual method?
- What does it mean to override a virtual method?
- What is an abstract method and when is it permitted?
- What is method overloading?
- What is the difference between an instance constructor and a static constructor?
- What is the primary difference between properties and fields?
- How do you make a property read-only?
- What is an indexer?
- What is an event, and what is true of it's type?
- What are event handlers?
- What is a class operator?
- What is a destructor?
- What's the main difference between classes and structs?
- What is an array?
- What is an array initializer?
- What is an interface, and what can it contain?
- What are enums?
- What is an enum's underlying type?
- What is a delegate?
- What is the purpose of attributes?
- What is a compilation unit in C#?
- What are the 3 steps in compiling a program?
- What encoding are C# files in? ie. ASCII?
- What is the purpose of lexical grammar?
- What is the purpose of syntactic grammar?
- What is contained within the first line of a grammar rule?
- When you see the suffix "opt" in a grammar rule, what does it mean?
- What are the five basic elements that make up the structure of a C# source file?
- Which of the 5 elements of a C# source file are relevant to the syntax of a C# file?
- What do line terminators do?
- What are the two forms of comments supported by C#, give examples.
- What are the 5 types of tokens?
- List ALL of the C# keywords
- What is a literal, and what are the 6 types of literals?
- Give an example of each type of literal.
- What is a verbatim literal string, and how is it created?
- What are the possible Pre-processing directive, what is their function, and what is their intended use?
As this week is largely an overview of the entire language and doesnt go into significant enough detail to warrent 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.
Week 1 Overview
Before I begin, let me tell you a bit about why I decided to use the C# Specification for the C# Workshop, some of the observed problems we're having so far, and how I plan to solve those problems.
First, I decided to use the C# Specification as the official documentation for the C# Workshop because it was both free, complete, and designed for intermediate to advanced programmers. You see, during the C++ Workshop we used a very rudimentary text designed for the complete beginner, and we also moved very slowly. The end result was that people got bored of the workshop, and eventually decided to quit. I wanted to avoid repeating a similar mistake, so instead I created a brand new one. In an attempt to accelerate the workshop to make it more interesting, and to make sure we were all able to use a freely available text, I chose the C# Specification. Unfortunately, I did so without considering how the participants of the C# workshop might be different from those of the C++ Workshop.
First, there's been a much larger interest in the C# Workshop than the C++ Workshop. This has guaranteed it's exposure to a larger audience of people. As well, unlike with C++ where many people were already experienced programmers, there's probably only a dozen or so very experienced C# programmers here on GDNet actively participating in the workshop (out of roughly 400 participants). And finally, C#, unlike C++ is advertised as a very user-friendly and easy to learn language. This has caused far more beginning programmers to join the C# workshop than joined the C++ workshop. What's the end result? The end result is that the C# specification isn't suitable as a beginning learning device, and consequently, not the best suited text for this workshop's audience.
Ok, so we're now working with a text which, although is a good, complete resource - may not be the best resource for the workshop. How do we fix it? Simple. With supplementary text. In specific, I will speak to those people who've volunteered as tutors and either myself or one of them will write an overview for each weekly thread which contains a more tutorial style introduction to the material. The overviews will not go into nearly as much depth as that covered in the specification, but it will provide more examples and it will present some of the most important information in a more human-readable format. I will be writing a partial overview below to give people an idea of what these overviews might be like. Please provide your feedback. If there's not enough interest or usefulness in writing such an overview for each weekly thread, please say so, as it's a time-consuming endeavor on top of an already time-consuming endeavor, and we dont want to burden either myself or the other tutors needlessly if the information and style presented here isn't useful to those beginning C#.
The text assigned to week 1 is chapters 1 and 2. The first chapter serves as an overview of the entire language, giving you just enough information to make you familiar with the terms and concepts of the C# language. Unfortunately, they dont give a slew of examples, nor do they frequently explain the how or the why of something. I dont want to make chapter 1 responsible for scaring people off, suggesting they need to learn the entire language within the first week, however people have already begun reading and are now becoming overwhelmed. At this point, the cat is out of the bag. The only way to move forward as I can see it, is to explain each of those topics a bit further, so they at least make enough sense that people can move forward without feeling like they were left in a deserted field and cluster-f&*!#d. But again, keep in mind that we will go into each topic in more details, one at a time, in the coming weeks. For now, you should just be familiar with the terminology and basic syntax presented here. Ok, let's get it started...
Hello World
It's customary when demonstrating a new language to use the "Hello World" example. Since I'm a fan of tradition, I'll do the same. I'll present the code first, and then explain it in more detail afterwards.
The above is a very simple example of a completely functional C# application. When compiled it create an executable assembly which, when executed, outputs "Hello World" (without quotes) to the console window. You should enter the above, without the line numbers, into your C# compiler, build and execute the above to see it in action.
Line 1 of the source code is what is called a class declaration. In C# all data and operations exist within a class, and there must be at least 1 class in any C# application. "But what is a class?" For now, just know that a class is a container for all data and operations within an application or library. We'll get into more detail about what a class is and how it's used in a few moments.
Lines 2 and 7 indicate the extents of the class declaration. Everything between the open '{' and close '}' brackets are considered part of the class. All functions, fields, events, delegates, etc...contained between the { and } are called Members of the class.
In this case, we've created a class called "HelloWorldProgram", and we've given it a single method (aka member function) called "Main". On line 3 you can see the declaration for the method called main. You'll also notice that there are two other words in that line - static and void.
Static is a keyword, which in this context, is used to indicate that the method Main is part of HelloWorldProgram, as a class, and does not require an instance of HelloWorldProgram as an Object. The difference between classes and objects will be explained later. For now, just recognize that all C# console programs must have a method called Main, and it must be declared static.
The second thing you'll see on that line is the type name "void". Void is actually a type used to indicate no type at all. Normally, a type name preceding a method name indicates what kind of value is returned from a method. When void is specified, it means the method doesn't return a value. In C#, the return value for main can either be 'int' or 'void'. If int is specified the programmer is responsible for returning a value. If void is specified, the programmer CANNOT return a value, and the value 0 is returned automagically.
On line 5 you see the real meat of the application. Up until this point, everything we've seen so far will exist in every C# console application you ever make. In fact, you could take out line 5, and just save everything else as a template application if you wanted to. (Note, you dont have to, Visual C# 2005 EE does that for you. Whenever you create a new console application, the class and Main are provided for you). On line 5 we have the line:
The above code may at first appear confusing, but when we break it down into sections, it makes much more sense. The first part is "System". Whenever a programmer writes instructions for a computer, they do so using variables which they create. These variables all have types, and every type has a name called its...wait for it...type name. To make sure the name of their types do not collide with other peoples types, they are grouped into namespaces. Think of it this way...lets say my name is Adam. At my university there may have been hundreds of Adams. How would someone know who I am by name from someone else with the same name? Simple, by also using my last name. If you were to say "Adam Smith", then people would immediately know you didn't mean "Adam Johnson". In other words, the last name of the individual helps to qualify WHICH individual is being referred to. Namespaces are the exact same thing. By grouping types into namespaces, we are in essence giving them a last name. And whenever there is confusion about which type to use with a similar name, a programmer can fully qualify it by identifying the namespace.
In the example above, we are wanting to reference the 'Console' class. But in order to do so I must instruct the compiler WHICH console I want to use. In this case, I have fully qualified which Console I want to use by also including its namespace, ie. System. There are alternative ways to indicate which namespace a type belongs to, but for the sake of this introduction I'll leave it at that.
The next part of the instruction above is "WriteLine". An identifier followed by ( followed by some optional information followed by ) is what's referred to as a method in C#. Using a method in that format invokes that method, causing it to execute code. In this case I'm invoking the WriteLine method of the Console class, in the System namespace. I'm also passing the method the parameter "Hello World". This, in whole, prints whatever I pass into WriteLine out to the console window.
Types & Variables
Now that we've taken a look at a basic C# application, lets make it a little more interesting. Lets start by adding some variables using the simple types that the C# language understands.
In the above example I've created a new class type called Character beginning on line 12. Character has one Field (variable) which is called name. Name is of type String. This is how you'd declare a publicly accessible field in C#. On line 5 of the Main method I create a new instance of myCharacter. On line 6 I assign the value "Jeromy Walsh" to my character's name. On line 8 I print the name of my character out to the console.
The above is just something to demonstrate how someone might use one of the simple data types. Among the other simple data types are int, byte, char, float, bool, and decimal. There are also enums and structs, but we'll talk more about that later. Lets expand the above to include some additional fields, which describe my Character class.
Each of the above fields use a different simple type, and each one accepts different types of values with different ranges. There is a complete table in your text which shows what types of data can go in each type, and what the possible ranges of values are.
Expressions
The next section of this overview deals with expressions. As indicated in your text, an expression can really be anything that returns a value, including allocation of new objects, comparisons, or even method invocations. But the thing people think of most when talking about expressions are mathematical expressions. That is, statements in the form 'x = m * a + b'. So I've created a quick example showing a practical set of expressions.
In the program above, you can see several expressions. First, lines 6-10 and again on lines 13-17 we are creating expression statements which assign values to the public fields of type "Character". On line 19 there is method invocation expression which returns void. And finally,
the majority of expressions are happening between lines 28 and 39. Let me explain these lines in a bit more details.
Lines 28, 31, and 34 are not expressions, they are technically local variable declarations, as we're allocating memory and declaring variables via an identifier which will be used throughout the rest of the method.
Line 29 is an expression which computes this character (rand's) damage output, based on a formula of his strength plus his level.
Line 32 is an expression which computes the enemies resistance, based on his level and his armor.
Line 34 is an expression where we compute the total damage done, by subtracting the resistance from the damage possible.
Line 36 is actually an if-statement, however the if-statement contains a boolean expression "totalDamage <= 0" which returns either true or false depending on the value of totalDamage. In the example, it returns false.
And finally, line 39 is an expression which uses the -= operator. This operator can be expanded into the form:
enemy.HitPoints = enemy.HitPoints - totalDamage;
You can now see the expression simply subtracts the totalDamage from the enemy's hitpoints, and then assigns it back to her hitpoins.
In C#, and especially in game development, the majority of your statements will either be expressions, declarations, or conditionals and branching such as if, else, switch, for, and while.
If you've found the above a more human-readable format for learning beginning C#, please let me know. Note, this is again just an overview of the information in week 1. If this format receives enough interest, myself or another tutor will write similar overviews for the remaining chapters. Also, please let me know if the above is detailed enough, not detailed enough, etc...What do you want more of, what do you want less of?
This workshop is really about all of you. If you're not getting what you want, or what you expected from the workshop, please speak up so we know what level we need to cater to. If there's enough interest in this format, I'll begin by completing the information below.
Arrays // Coming soon...
Structs // Coming soon...
Enums // Coming soon...
Classes & Objects // Coming soon...
Interfaces // Coming soon...
Delegates // Coming soon...
Attributes // Coming soon...
Before I begin, let me tell you a bit about why I decided to use the C# Specification for the C# Workshop, some of the observed problems we're having so far, and how I plan to solve those problems.
First, I decided to use the C# Specification as the official documentation for the C# Workshop because it was both free, complete, and designed for intermediate to advanced programmers. You see, during the C++ Workshop we used a very rudimentary text designed for the complete beginner, and we also moved very slowly. The end result was that people got bored of the workshop, and eventually decided to quit. I wanted to avoid repeating a similar mistake, so instead I created a brand new one. In an attempt to accelerate the workshop to make it more interesting, and to make sure we were all able to use a freely available text, I chose the C# Specification. Unfortunately, I did so without considering how the participants of the C# workshop might be different from those of the C++ Workshop.
First, there's been a much larger interest in the C# Workshop than the C++ Workshop. This has guaranteed it's exposure to a larger audience of people. As well, unlike with C++ where many people were already experienced programmers, there's probably only a dozen or so very experienced C# programmers here on GDNet actively participating in the workshop (out of roughly 400 participants). And finally, C#, unlike C++ is advertised as a very user-friendly and easy to learn language. This has caused far more beginning programmers to join the C# workshop than joined the C++ workshop. What's the end result? The end result is that the C# specification isn't suitable as a beginning learning device, and consequently, not the best suited text for this workshop's audience.
Ok, so we're now working with a text which, although is a good, complete resource - may not be the best resource for the workshop. How do we fix it? Simple. With supplementary text. In specific, I will speak to those people who've volunteered as tutors and either myself or one of them will write an overview for each weekly thread which contains a more tutorial style introduction to the material. The overviews will not go into nearly as much depth as that covered in the specification, but it will provide more examples and it will present some of the most important information in a more human-readable format. I will be writing a partial overview below to give people an idea of what these overviews might be like. Please provide your feedback. If there's not enough interest or usefulness in writing such an overview for each weekly thread, please say so, as it's a time-consuming endeavor on top of an already time-consuming endeavor, and we dont want to burden either myself or the other tutors needlessly if the information and style presented here isn't useful to those beginning C#.
The text assigned to week 1 is chapters 1 and 2. The first chapter serves as an overview of the entire language, giving you just enough information to make you familiar with the terms and concepts of the C# language. Unfortunately, they dont give a slew of examples, nor do they frequently explain the how or the why of something. I dont want to make chapter 1 responsible for scaring people off, suggesting they need to learn the entire language within the first week, however people have already begun reading and are now becoming overwhelmed. At this point, the cat is out of the bag. The only way to move forward as I can see it, is to explain each of those topics a bit further, so they at least make enough sense that people can move forward without feeling like they were left in a deserted field and cluster-f&*!#d. But again, keep in mind that we will go into each topic in more details, one at a time, in the coming weeks. For now, you should just be familiar with the terminology and basic syntax presented here. Ok, let's get it started...
Hello World
It's customary when demonstrating a new language to use the "Hello World" example. Since I'm a fan of tradition, I'll do the same. I'll present the code first, and then explain it in more detail afterwards.
1: class HelloWorldProgram2: {3: static void Main()4: {5: System.Console.WriteLine("Hello World");6: }7: } The above is a very simple example of a completely functional C# application. When compiled it create an executable assembly which, when executed, outputs "Hello World" (without quotes) to the console window. You should enter the above, without the line numbers, into your C# compiler, build and execute the above to see it in action.
Line 1 of the source code is what is called a class declaration. In C# all data and operations exist within a class, and there must be at least 1 class in any C# application. "But what is a class?" For now, just know that a class is a container for all data and operations within an application or library. We'll get into more detail about what a class is and how it's used in a few moments.
Lines 2 and 7 indicate the extents of the class declaration. Everything between the open '{' and close '}' brackets are considered part of the class. All functions, fields, events, delegates, etc...contained between the { and } are called Members of the class.
In this case, we've created a class called "HelloWorldProgram", and we've given it a single method (aka member function) called "Main". On line 3 you can see the declaration for the method called main. You'll also notice that there are two other words in that line - static and void.
Static is a keyword, which in this context, is used to indicate that the method Main is part of HelloWorldProgram, as a class, and does not require an instance of HelloWorldProgram as an Object. The difference between classes and objects will be explained later. For now, just recognize that all C# console programs must have a method called Main, and it must be declared static.
The second thing you'll see on that line is the type name "void". Void is actually a type used to indicate no type at all. Normally, a type name preceding a method name indicates what kind of value is returned from a method. When void is specified, it means the method doesn't return a value. In C#, the return value for main can either be 'int' or 'void'. If int is specified the programmer is responsible for returning a value. If void is specified, the programmer CANNOT return a value, and the value 0 is returned automagically.
On line 5 you see the real meat of the application. Up until this point, everything we've seen so far will exist in every C# console application you ever make. In fact, you could take out line 5, and just save everything else as a template application if you wanted to. (Note, you dont have to, Visual C# 2005 EE does that for you. Whenever you create a new console application, the class and Main are provided for you). On line 5 we have the line:
System.Console.WriteLine("Hello World");The above code may at first appear confusing, but when we break it down into sections, it makes much more sense. The first part is "System". Whenever a programmer writes instructions for a computer, they do so using variables which they create. These variables all have types, and every type has a name called its...wait for it...type name. To make sure the name of their types do not collide with other peoples types, they are grouped into namespaces. Think of it this way...lets say my name is Adam. At my university there may have been hundreds of Adams. How would someone know who I am by name from someone else with the same name? Simple, by also using my last name. If you were to say "Adam Smith", then people would immediately know you didn't mean "Adam Johnson". In other words, the last name of the individual helps to qualify WHICH individual is being referred to. Namespaces are the exact same thing. By grouping types into namespaces, we are in essence giving them a last name. And whenever there is confusion about which type to use with a similar name, a programmer can fully qualify it by identifying the namespace.
In the example above, we are wanting to reference the 'Console' class. But in order to do so I must instruct the compiler WHICH console I want to use. In this case, I have fully qualified which Console I want to use by also including its namespace, ie. System. There are alternative ways to indicate which namespace a type belongs to, but for the sake of this introduction I'll leave it at that.
The next part of the instruction above is "WriteLine". An identifier followed by ( followed by some optional information followed by ) is what's referred to as a method in C#. Using a method in that format invokes that method, causing it to execute code. In this case I'm invoking the WriteLine method of the Console class, in the System namespace. I'm also passing the method the parameter "Hello World". This, in whole, prints whatever I pass into WriteLine out to the console window.
Types & Variables
Now that we've taken a look at a basic C# application, lets make it a little more interesting. Lets start by adding some variables using the simple types that the C# language understands.
1: class CharacterNameProgram2: {3: static void Main()4: {5: Character myCharacter = new Character();6: myCharacter.name = "Jeromy Walsh";7: 8: System.Console.WriteLine(myCharacter.name);9: }10: }11: 12: class Character13: {14: public System.String name;14: }In the above example I've created a new class type called Character beginning on line 12. Character has one Field (variable) which is called name. Name is of type String. This is how you'd declare a publicly accessible field in C#. On line 5 of the Main method I create a new instance of myCharacter. On line 6 I assign the value "Jeromy Walsh" to my character's name. On line 8 I print the name of my character out to the console.
The above is just something to demonstrate how someone might use one of the simple data types. Among the other simple data types are int, byte, char, float, bool, and decimal. There are also enums and structs, but we'll talk more about that later. Lets expand the above to include some additional fields, which describe my Character class.
1: class CharacterInfoProgram2: {3: static void Main()4: {5: Character myCharacter = new Character();6: myCharacter.name = "Jeromy Walsh";7: myCharacter.age = 27; 8: myCharacter.weight = 165;9: myCharacter.middleInitial = 'L';10: 11: System.Console.WriteLine(myCharacter.name);12: }13: }14: 15: class Character16: {17: public System.String name;18: public byte age;19: public int weight;20: public char middleInitial;21: }Each of the above fields use a different simple type, and each one accepts different types of values with different ranges. There is a complete table in your text which shows what types of data can go in each type, and what the possible ranges of values are.
Expressions
The next section of this overview deals with expressions. As indicated in your text, an expression can really be anything that returns a value, including allocation of new objects, comparisons, or even method invocations. But the thing people think of most when talking about expressions are mathematical expressions. That is, statements in the form 'x = m * a + b'. So I've created a quick example showing a practical set of expressions.
1: class CharacterFightProgram2: {3: static void Main()4: {5: Character rand = new Character();6: rand.Name = "Rand";7: rand.Level = 5;8: rand.HitPoints = 50;9: rand.Strength = 5;10: rand.Armor = 5;11: 12: Character Semirhage = new Character();13: Semirhage.Name = "Semirhage";14: Semirhage.Level = 4;15: Semirhage.HitPoints = 40;16: Semirhage.Strength = 4;17: Semirhage.Armor = 4;18: 19: rand.Attack(Semirhage);20: System.Console.WriteLine("{0}'s hitpoint are now {1}.", Semirhage.Name, Semirhage.HitPoints);21: }22: }23: 24: class Character25: {26: public void Attack(Character enemy)27: {28: int damage = 0;29: damage = Level + Strength;30: 31: int resistance = 0;32: resistance = enemy.Level + enemy.Armor;33: 34: int totalDamage = damage - resistance;35: 36: if (totalDamage <= 0) 37: totalDamage = 1;38: 39: enemy.HitPoints -= totalDamage;40: }41: 42: public int HitPoints43: {44: get { return m_Hitpoints; }45: set46: {47: if (value < 0) m_Hitpoints = 0;48: else m_Hitpoints = value;49 }50: }51: 52: public System.String Name; 53: public int Level;54: public int Strength;55: public int Armor;56: 57: private int m_Hitpoints;58: }In the program above, you can see several expressions. First, lines 6-10 and again on lines 13-17 we are creating expression statements which assign values to the public fields of type "Character". On line 19 there is method invocation expression which returns void. And finally,
the majority of expressions are happening between lines 28 and 39. Let me explain these lines in a bit more details.
Lines 28, 31, and 34 are not expressions, they are technically local variable declarations, as we're allocating memory and declaring variables via an identifier which will be used throughout the rest of the method.
Line 29 is an expression which computes this character (rand's) damage output, based on a formula of his strength plus his level.
Line 32 is an expression which computes the enemies resistance, based on his level and his armor.
Line 34 is an expression where we compute the total damage done, by subtracting the resistance from the damage possible.
Line 36 is actually an if-statement, however the if-statement contains a boolean expression "totalDamage <= 0" which returns either true or false depending on the value of totalDamage. In the example, it returns false.
And finally, line 39 is an expression which uses the -= operator. This operator can be expanded into the form:
enemy.HitPoints = enemy.HitPoints - totalDamage;
You can now see the expression simply subtracts the totalDamage from the enemy's hitpoints, and then assigns it back to her hitpoins.
In C#, and especially in game development, the majority of your statements will either be expressions, declarations, or conditionals and branching such as if, else, switch, for, and while.
If you've found the above a more human-readable format for learning beginning C#, please let me know. Note, this is again just an overview of the information in week 1. If this format receives enough interest, myself or another tutor will write similar overviews for the remaining chapters. Also, please let me know if the above is detailed enough, not detailed enough, etc...What do you want more of, what do you want less of?
This workshop is really about all of you. If you're not getting what you want, or what you expected from the workshop, please speak up so we know what level we need to cater to. If there's enough interest in this format, I'll begin by completing the information below.
Arrays // Coming soon...
Structs // Coming soon...
Enums // Coming soon...
Classes & Objects // Coming soon...
Interfaces // Coming soon...
Delegates // Coming soon...
Attributes // Coming soon...
I have created a new thread for week 1 specifically designed for beginners. People with little or no previous programming experience, or people who feel their question is of a more beginner nature should post their questions in this thread.
Those with a good amount of previous programming experience, or who need clarification on functionality differences between C# and C++ should post their questions in the week 1 thread marked as advanced.
These threads for week 1 will remain, and future weeks may or may not be split up in such a fashion. The GDNet staff and moderators are looking at a more long-term solution to make posting questions for Workshops easier. I'll keep you updated.
Finally, due to the general feeling that the beginners are having a hard time grasping the basic concepts, we will be extending week 1 by another week. That is, week 1 will actually be active for 2 weeks.
grasping the basic concepts, we will be extending week 1 by another week. That is, week 1 will actually be active for 2 weeks.
The beginner thread is located Here.
While the advanced thread is located Here.
Cheers!
Those with a good amount of previous programming experience, or who need clarification on functionality differences between C# and C++ should post their questions in the week 1 thread marked as advanced.
These threads for week 1 will remain, and future weeks may or may not be split up in such a fashion. The GDNet staff and moderators are looking at a more long-term solution to make posting questions for Workshops easier. I'll keep you updated.
Finally, due to the general feeling that the beginners are having a hard time grasping the basic concepts, we will be extending week 1 by another week. That is, week 1 will actually be active for 2 weeks.
grasping the basic concepts, we will be extending week 1 by another week. That is, week 1 will actually be active for 2 weeks.
The beginner thread is located Here.
While the advanced thread is located Here.
Cheers!
I think this is a very good idea. The beginners would get quickly overwhelmed with the level of detail in the other thread.
I'm here to help as a tutor, so any questions, ask away.. I hate getting bogged down in syntax, so I'll be here in the beginner thread for a while :)
I'm here to help as a tutor, so any questions, ask away.. I hate getting bogged down in syntax, so I'll be here in the beginner thread for a while :)
I think splitting the threads in two is a great idea. I think you writing out the code and giving descriptions on a step by step basis really works. I have been learning C# for a few months now and I find myself making silly mistakes and often over complicating things. It is nice to just go back sometimes and see a simple explanation. Also I really think repitition is the key and the more code you see and preferably write the better it is. I try to well i dont try I do write code everyday, at home and at work. It doesnt matter what it is. I write a project at work with my freind and mentor and then I come home and try to rewrite myself. I will also write projects out of a book I am reading at home and then when I get to work I will try to rewrite those projects. It may just be me but it is harder than it sounds. Dedication and Repition for me will be the key and for others I think as well.
By the way I love the RPG project and I cant wait to start getting into projects. So one thing I would like are more simple writing projects. Nothing more than 10 lines of code but just so we keep writing code so it can stick in the head more. I do this on the side on my own but the more the better.
By the way I love the RPG project and I cant wait to start getting into projects. So one thing I would like are more simple writing projects. Nothing more than 10 lines of code but just so we keep writing code so it can stick in the head more. I do this on the side on my own but the more the better.
Can you give us a summary of chapter 2 too? Cause that's the one that has me scratching my head.
What in particular in chapter 2 is confusing you? I mean, the whole thing is confusing, but to write an effective overview it would be nice to see which things need the most explaining.
Cheers!
Cheers!
Is it just me or does C++ seem a hell of a lot easier? I started learning C++ a couple months ago, and have a firm grasp on the language, but jeez, C# is confusing the hell out of me. It may be just the spec we are reading.
I'm going to reread Chapter 1 again right now and see if it helps to understand it.
I'm going to reread Chapter 1 again right now and see if it helps to understand it.
Quote:
Original post by Menace2Society
Can you give us a summary of chapter 2 too? Cause that's the one that has me scratching my head.
Chapter 2 is a summary of the formal grammar of the language. Essentially /* this is a comment */ in a way that is clear perhaps only to those who've a formal CS background... The individual chapters will do more explicit description hopefully, but let's see if I can't summarize it into something more comprehensible. Chapter numbers will be included.
2.1 Programs
The code for a C# program is stored in Unicode text files. Unicode if you don't know, is a text format that allows a whole ton of characters, meaning non-English characters are fair game in the source code. In the spec you might see the term Compilation Unit which is nothing more than a source file.
2.2 Grammars
Technically, your source code is first broken into chunks (tokens) before the compiler turns it into something that runs. [opinion]Something you needn't know.[/opinion]
2.2.1 Grammar Notation
This is a small intro to how formal grammars are being described by the document. Things in fixed width font are literally that text. Things in italics refer to something else.
An example (dots for spacing):
colored_animal:
........number[opt] color animal
color: one of
........blue red white
animal: one of
........cow sheep pig
number: one of
........1 2 3 4 5 6 7 8 9
This describes the grammar element for a colored animal. It optionally takes a number (which is 1,2,3,4,5,6,7,8, or 9) followed by a color (blue red or white), followed by an animal (cow sheep or pig).
Thus "blue pig", "6 red sheep", and "9 blue cow" are all grammatically correct.
2.2.2 - 2.2.3
The chapters indicate where to find the two grammars.
2.3 Lexical Analysis
Lexical analysis is taking source code and breaking it into tokens. This means mostly tossing out whitespace, newlines, comments, and pre-processor directives (more on these later).
2.3.1 Line Terminators
A list of the official newline characters. In C# Express, there's essentially one of these at the end of every line.
2.3.2 Comments
Comments are bits of text that are not part of the code and just there for others reading your code.
C# supports C++ style /* */ (comment everything between) and // (comment the rest of the line) comments. The example on pages 34-35 is good.
2.3.3 Whitespace
Pretty much anything that is space in your editor is whitespace. Whitespace has no meaning beyond token separation in C#.
2.4 Tokens
Tokens are the meat of the program. They're what is kept, and passed along to the compiler to turn into a running program. There are different sorts of tokens:
2.4.1 Unicode escape sequences
First off, an escape sequence is something that looks like \something. They're used to represent something that isn't on most keyboards or means something to the compiler. (You use them to put a double-quote inside text [which is between double quotes] for example).
\u#### (replace with the unicode code in hex) can then be used to represent a unicode character, even if you can't type it with your keyboard.
2.4.2 Identifiers
Identifiers are labels. When you declare a variable, you give it a name. When you declare a class, you give it a name. These names are identifiers.
If I remember correctly, names are restricted to a letter or underscore followed by any number of letters, underscores, or digits.
2.4.3 Keyword
A keyword is a word which is reserved by the language, and this part of the doc has a list of them.
2.4.4 Literals
true, false, null, a character between single quotes, text between double quotes, a number... These are hard-coded values within the code. There are a few suffixes (to specify what type a number is for example) and options to use, but more often than not just typing in the number, quoted text, etc. will be sufficient.
Here is also a list of escape sequences. Once more, these are ways of representing characters which your keyboard doesn't have or would cause problems. The 'at' symbol (@) before a string disables the escape sequences within (pg. 42 for example)
2.4.5 Operators
Mathematical operations are supported in C#, and their operators are tokens specifying the various operations. These operations will be described later in the specification. The list of them is on page 43.
2.5 PreProcessing Directives
Pre-processing directives start with a pound sign (#) and do not show up often in code. Remember that anything like #if is a pre-processing directive and look it up when you encounter it.
For C/C++ users: Since C#'s pre-processor directives are dumped before tokens are ever processed, that means #define and the such cannot be used by actual code.
I think its great that you're using game-oriented code examples to explain these concepts. Please keep doing that. And thanks for your hard work, its very much appreciated.
Love the idea of breaking the threads apart. Alot of information in the other thread was geared towards intermediate to advanced programmers IMO. Having to search through it all to attempt to find an answer to a question that I posted was a bit tedious. I think as we get a little further along, where we are actually coding, maybe the summaries will not be needed. Although with these two initial chapters, and the breadth of data contained, I am glad jwalsh did that. It did help me to get a little better grasp of the text.
Just for inspiration for some of you other budding programmers out there, this newb is 35 (pushing 36) years old. What's that old saying? You cant teach an old dog new tricks? Hahahahha!!! We will see about that. When it comes time to complete that final project, I hope to see all of you right there with me!!
Thanks,
Shawn
*Edit* - BTW, if anyone around here games, or uses Teamspeak, my clan and I have a teamspeak server. If anyone is interested in the IP or our clans website, shoot me a PM. Maybe we can work through the workshop together utilizing TS (Teamspeak) to overcome some hurdles....just a thought.
Just for inspiration for some of you other budding programmers out there, this newb is 35 (pushing 36) years old. What's that old saying? You cant teach an old dog new tricks? Hahahahha!!! We will see about that. When it comes time to complete that final project, I hope to see all of you right there with me!!
Thanks,
Shawn
*Edit* - BTW, if anyone around here games, or uses Teamspeak, my clan and I have a teamspeak server. If anyone is interested in the IP or our clans website, shoot me a PM. Maybe we can work through the workshop together utilizing TS (Teamspeak) to overcome some hurdles....just a thought.
No one has anymore beginning C# questions? I'll post more of my overview this weekend.
Cheers!
Cheers!
Quote:
Original post by JWalsh
No one has anymore beginning C# questions? I'll post more of my overview this weekend.
Cheers!
I think your overview answered any questions dealing with the subjects you've written so far, and people are just waiting for the rest of it before they go asking.
Thank you JWalsh for taking the time to run the workshop. I've always wanted to program but procrastination usually gets the better of me. If I do have any questions I will be sure to ask.
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.
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.
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.
- What is component-oriented programming?
- What are the keys to software components in C#?
- What is Garbage Collection?
- What is exception Handling?
- What benefits do type safety provide you in C#?
- What is a unified type system?
- What are the benefits of a unified type system?
- What's the purpose of namespaces?
- What directive allows unqualified use of the members of a namespace?
- What is the entry point of a C# Console application?
- What's the name of the C# Runtime libraries?
- What are the key organizational concepts in C#?
- What two things do C# assemblies contain and what form are they in?
- What happens to the IL instructions just before the code is executed?
- When are forward decelerations needed in C#?
- What are the two kinds of variable types in C# what's the difference?
- How are C#'s value types subdivided?
- How are C#'s reference types subdivided?
- What is the encoding of a C# character, and how much memory does a single character require?
- What are the sizes of each of the Simple Types, and their range of values?
- Which 5 categories of C# types are user-definable types?
- Give an overview of each of the 5 types.
- What is "boxing" and "unboxing"
- What are expressions?
- What is the relationship between operators and operands in an expression?
- What is an operator's precedence?
- What is operator overloading?
- What are the different kinds of C# statements, and what do they do??
- What is a class?
- Create an example class named Character. Dont worry about members, methods, or properties
- What operator is used to create a new instance of a class? What's the syntax to create a Character object?
- What are the different types of members of a class?
- What are the 5 types of Accessibility used on a class's members?
- What does inheritance mean?
- What is a field?
- What is the difference between a static and non-static field?
- What is a method of a class?
- What's the difference between static and non-static methods?
- What are parameters?
- What are return types?
- What does a signature of a method consist of?
- What are the 4 types of parameters and how are they used?
- What is a static method?
- What is an instance method?
- What's the difference between a virtual and non-virtual method?
- What does it mean to override a virtual method?
- What is an abstract method and when is it permitted?
- What is method overloading?
- What is the difference between an instance constructor and a static constructor?
- What is the primary difference between properties and fields?
- How do you make a property read-only?
- What is an indexer?
- What is an event, and what is true of it's type?
- What are event handlers?
- What is a class operator?
- What is a destructor?
- What's the main difference between classes and structs?
- What is an array?
- What is an array initializer?
- What is an interface, and what can it contain?
- What are enums?
- What is an enum's underlying type?
- What is a delegate?
- What is the purpose of attributes?
- What is a compilation unit in C#?
- What are the 3 steps in compiling a program?
- What encoding are C# files in? ie. ASCII?
- What is the purpose of lexical grammar?
- What is the purpose of syntactic grammar?
- What is contained within the first line of a grammar rule?
- When you see the suffix "opt" in a grammar rule, what does it mean?
- What are the five basic elements that make up the structure of a C# source file?
- Which of the 5 elements of a C# source file are relevant to the syntax of a C# file?
- What do line terminators do?
- What are the two forms of comments supported by C#, give examples.
- What are the 5 types of tokens?
- List ALL of the C# keywords
- What is a literal, and what are the 6 types of literals?
- Give an example of each type of literal.
- What is a verbatim literal string, and how is it created?
- What are the possible Pre-processing directive, what is their function, and what is their intended use?
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
Garbage collection automatically reclaims memory occupied by unused objects;
exception handling provides a structured and extensible approach to error detection and recovery;
design of the language makes it impossible to have uninitialized variables, to index arrays beyond their bounds, or to perform unchecked type casts.
All C# types, including primitive types such as int and double, inherit from a single root object type.
all types share a set of common operations, and values of any type can be stored, transported, and operated upon in a consistent manner.
Namespaces provide a hierarchical means of organizing C# programs and libraries.
The 'using' directive.
A static method named "main."
The .NET Framework Library
Programs, namespaces, types, members, and assemblies.
Executable code in the form of Intermediate Language and symbolic information in the form of metadata
It is converted into processor-specific code by the JIT compiler of the .NET CLR.
Never.
Valye types and reference types. Value types store data directly, reference types store references to their data.
simple types, enum types, and struct types.
Class types, interface types, array types, and delegate types.
Unicode encoding. It requires 16-bits.
####
class, struct, interface, enum, and delegate.
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.
The process of casting a C# value type to an object.
Expressions are constructed from operands and operators
Operators tell what operation to perform on the operands.
A rule which governs the order in which the operator is evaluated relative to other operators.
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.
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.
A class is a data structure that combines state (fields) and actions (methods and other function members) in a single unit.
public class Character
{
}
The new operator
Character myCharacter = new Character();
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
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
Inheritance means that a class implicitly contains all members of its base class, except for the constructors of the base class
A field is a variable that is associated with a class or with an instance of a class.
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.
A method is a member that implements a computation or action that can be performed by an object or class.
Static methods are accessible from the class, while non-static are accessible from the instances of the class, or "objects."
list of arguments, which represent values or variable references passed to the method
specifies the type of the value computed and returned by the method
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.
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.
A method declared with a static modifier. It does not operaote on a specific instance of a class, and can only access static members.
Any method created without the static modifier. It operates on specific instance of the class, and can access both static and non-static members.
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.
The method overrides an inherited virtual method with the same signature, thus providing a new implementation for that method.
A method with no implementation. It is only permitted in classes also declared abstract.
Method overloading permits multiple methods in the same class to have the same name, so long as they have unique signatures.
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.
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.
Dont provide a set method.
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.
An event is a member that enables a class or object to provide notifications. The type must always be a delegate.
Event handlers are methods attached to an event using the += operator and removed with the -= operator.
Its a member that defines (re-defines) the meaning of applying a particular expression operator to instances of the class.
A member that implements the actions required to destruct an instance of a class - specifically non-garbage collected member data.
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.
An array is a data structure that contains a number of variables of the same type that are accessed through computed indices.
A way of initializing the values within an array during construction of the array.
An interface defines a contract that can be implemented by classes and structs. An interface can contain methods, properties, events, and indexers.
enums are a value type which contain a set of named, symbolic constants.
All enums have an underlying integral type. Those that are not specified have default underlying type of 'int'.
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.
To allow user-defined types of declarative information that can be attached to program entities and retrieved at run-time.
It's a source file
1. Transformation
2. Lexical Analysis
3. Syntatic Analysis
Unicode
It defines how Unicode characters are combined to form line terminators, white space, comments, tokens, and pre-processing directives.
Defines how the tokens resulting from the lexical grammar are combined to form C# programs.
The non-terminal symbol being defined, followed by a colon.
It means the previous term is optional.
Line terminators, white space, comments, tokens, and pre-processing directives.
The tokens.
divide the characters of C# source files into lines.
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.
Identifiers, Keywords, literals, operators, and punctuators.
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 whileA source code representation of an actual value.
boolean
integer
real
character
string
null
true
200
200.23
'c'
"Hello, World"
null
A verbatim literal is one with a @ at the beginning, and in a verbatim string, escape characters are not interpreted.
#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.
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"); }}
Beginner Question.
I have visual studio.net 2005 Standard Ed.
Ok I did all excersies no bugs. I build than test it.. It pops up with command console than disappears in like 1/2 a second.. How do I have it stay?
I remember in c++ I had something 0;
Thanks
P.S Good work. Keep it up :-)
-Zac Karpinski
I have visual studio.net 2005 Standard Ed.
Ok I did all excersies no bugs. I build than test it.. It pops up with command console than disappears in like 1/2 a second.. How do I have it stay?
I remember in c++ I had something 0;
Thanks
P.S Good work. Keep it up :-)
-Zac Karpinski
Quote:
Original post by zKarp
Beginner Question.
I have visual studio.net 2005 Standard Ed.
Ok I did all excersies no bugs. I build than test it.. It pops up with command console than disappears in like 1/2 a second.. How do I have it stay?
I remember in c++ I had something 0;
Thanks
P.S Good work. Keep it up :-)
-Zac Karpinski
I believe ctrl-f5 runs the app and keeps the console window open. Failing that, add System.Console.ReadKey(); before your return statement (if you have one).
Quote:
Original post by Andorien
I believe ctrl-f5 runs the app and keeps the console window open. Failing that, add System.Console.ReadKey(); before your return statement (if you have one).
Thanks the ctrl-f5 works.
and yea return 0; is what i used in C++. :-) *I think*
Thanks again Andorien
-Zac Karpinski
Quote:
Original post by Exershio
Is it just me or does C++ seem a hell of a lot easier? I started learning C++ a couple months ago, and have a firm grasp on the language, but jeez, C# is confusing the hell out of me. It may be just the spec we are reading.
I'm going to reread Chapter 1 again right now and see if it helps to understand it.
IMO C# looks a lot easier than C++. But that may be because i have a Java background.
C# seems to be more Java-oriented than C++ oriented, am I right? (I'n not a C++ buff, so I can't judge)
I mean:
C#:
1: class HelloWorldProgram2: {3: static void Main()4: {5: System.Console.WriteLine("Hello World");6: }7: } Java:
class HellowWorldProgram { public static void main(String[] args) { System.out.println("Hello World"); }}Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement