Advertisement

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

Started by July 01, 2007 12:15 AM
337 comments, last by paulecoyote 17 years, 2 months ago
Thank you ChaosUK. That link was just what I needed.
I'm reading through it now & things are finally starting to fall into place :D



I've never done any coding before, so I'm completely lost. Help me please
Advertisement
I'm pretty sure about interfaces but correct me if i'm wrong.
I assign an interface like so:

interface Move
{
void Walk()
void Run()
}

I cannot specify parameters like Walk(int a, int b) in the implementation in order to force those parameters in the derived method, right?
Since I've decided to not return anything, can I override this and actually return something in the derived method?

Could anyone give me a RPG example of the use of enums and delegates? I think the explanation is a bit vague in the spesification. An example might help me see how it can be put to good use.

Is this operator overloading? for(int i = 0; (i + val) < num; i++){}

Lastly, I understand the use of properties and indexing, but can any of you show me an example of it being declared in a class and then within the Main() method?
The spesification diddn't really show an example of how an indexer is setup in a class. IE, will it automatically store values like an array or do you have to create a body and manually set up an array of sorts to collect the values?
Quote: Original post by Vod
C# has a unified type system. All C# types, including primitive types such as int and double, inherit from a single root object type. Thus, all types share a set of common operations, and values of any type can be stored, transported, and operated upon in a consistent manner.

inherit from a single root object type What does this mean? Does this mean 'object' as in object/class type of thing (classes confuse the bejesus out of me -see below)

all types share a set of common operations Why wouldn't they? Surely an int, for example, will always act like an int anyway?


I'm no expert so maybe there will be better explanations from other users but yeah these sorts of things can be quite confusing especially since the term object is normally used to refer to an instance of a class, that is if you create a class like:

class myClass
{
...
}

and then use it in your program like:

myClass test = new myClass();

test is an instance of myClass but it is also referred to as an object.

Object in the text you quoted is not used in the context I explained above. In this case I understand object is actually a class which is the basis for ints, doubles etc. It is used as an abstract concept - a vague description of what something is.

By "all types share a set of common operations", my understanding of this is that the object class contains certain methods(operations which you can perform on an an instance of the object class) which because ints, doubles, floats etc are all derived from the object class means that these methods are also available to ints etc.

You can check this on your IDE by creating an object like:

object test = new object();

then typing test. - you should then see a list of methods that the instance of object can perform. Now if you create an int object like:

int num;
then type in num. - then you should see a list of methods that int can perform but you'll notice that it actually shares some of the same methods that you can perform on an object type. In fact anything derived from object will always inherit the methods that can be performed on object therefore "all types share a set of common operations".

I'm not sure if this has made things more confusing or clear but generally that's my understanding of the text.
How about them apples?
Quote: The following site might help you vod on understanding classes and objects -

http://www.publicjoe.f9.co.uk/csharp1/csharp03.html

Its written for beginners.


Thanks for that. I'll post it at the beginning of the thread as an additional resource. As well, I'm thinking I'm going to have to write something like that myself for this first week's information. I plan on doing something similar to that for each of the coming weeks as well.

Quote: I've never done any coding before, so I'm completely lost. Help me please

Fair enough. Check out the link provided above. It's a more graceful introduction/overview that the one provided in the specification. As I said, I'll also be posting my own overview before the week is up to make sure people are familiar with the terms enough to move forward.

Remember, Week 1 isn't really about learning to program in C#, its more about learning to recognize the basic concepts and getting familiar with the terminology. If you can answer the review questions by the end of the week, you'll know everything you need from this week's reading to move forward...ok, well, you'll want to read my overview as well. =)
Quote: I'm pretty sure about interfaces but correct me if i'm wrong.
I assign an interface like so:

interface Move
{
void Walk()
void Run()
}

I cannot specify parameters like Walk(int a, int b) in the implementation in order to force those parameters in the derived method, right?

hrmm...where to start. First, you need to make sure and put a ';' at the end of each method declaration. Like so:
interface Move{    void Walk();    void Run();}

Next, it's perfectly fine to specify methods which have parameters. That's actually kind of the point of interfaces. Let say I have an interface with a "Walk" method, if I want the classes which implement the walk method to have parameters in the declaration, then I just put the parameters in the interface. The full signature and return type of the methods is part of the contract, this means name, as well as parameters.
interface Move{    void Walk(int a, int b);  // Perfectly valid. Now all implementors must provide this method with the same parameters    void Run();}

Quote: Since I've decided to not return anything, can I override this and actually return something in the derived method?


No. For interfaces, the return type is part of the contract. If you specify "void" as the return type, then all classes which implement your interface must also specify "void" as the return type for their implementation.
Quote: Could anyone give me a RPG example of the use of enums and delegates? I think the explanation is a bit vague in the spesification. An example might help me see how it can be put to good use.


I'd be happy to give an example of an enum, however delegates are an intermediate concept, something I'd like to wait until later in the workshop to go over more thoroughly. For now, just be aware that delegates are objects which allow you to pass around methods as parameters, etc...They're primarily used in events for callbacks. Here's your enum example.

using System;enum HairColor{    Brown,           Cinnamon,    Black,           Blonde,    Golden,            Auburn,    Red,            Scarlet,    White,    Gray}class Character{    public HairColor HairColor    {        get { return m_HairColor; }        set { m_HairColor = value; }    }    private HairColor m_HairColor;}class Program{    static void Main(string[] args)    {        Character myCharacter = new Character();        myCharacter.HairColor = HairColor.Auburn;        System.Console.WriteLine("My hair color is {0}", myCharacter.HairColor);    }}    

In the above example I create an enumeration named HairColor, a class called Character, and another class called Program, all in the global namespace. The enum HairColor defines available hair colors for my character.

To make this possible I create a member variable (Field) in Character of type HairColor (my user-defined enum type). Then, to practice proper OO design, I provided a Property called HairColor (It's good practice according to the Microsoft C# style Guideline to name Properties the same as their data types whenever possible) in order to get/set a value for m_HairColor.

Finally, in the program's main function I create an instance of Character, and I assign it's HairColor property the value HairColor.Auburn. This is the way enums are used in C#. You specify the enum typename, followed by the value of the enum you wish to use. Just for good measure I write out to the console the color of my hair. In this case, it prints out:

"My hair color is Auburn"

Why does is do this? Because I told it to print myCharacter.HairColor which takes the value of my hair color (ie. HairColor.Auburn) and converts it to a string. With enums, converting the value to a string always creates a string which has the value equal to the name of the value in the enum. In this case, "Auburn".

Finally, the primary point of this week's workshop is just to make sure you understand the general concepts. In coming weeks we'll go into more detail about indexers and properties than you can imagine. However, for now, it's sufficient to know that indexers allow you to create methods which grant access to your data via a computed index, and properties allow you to get/set the value of your Fields or computed data. There is an example Property above, however.

Look for my Week 1 Overview in a few days. I hope this was helpful.

[Edited by - JWalsh on July 4, 2007 11:07:16 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
Quote: Original post by JWalsh
Why does is do this? Because I told it to print myCharacter.HairColor.ToString() which takes the value of my hair color (ie. HairColor.Auburn) and converts it to a string. With enums, converting the value to a string always creates a string which has the value equal to the name of the value in the enum. In this case, "Auburn".

Note that you do not need the ToString() call, as that is implicitly performed for you. As such you could replace that line with: System.Console.WriteLine( "My hair color is " + myCharacter.HairColor);. However, to be proper in the usage of Console.WriteLine (and strings in general) it really should be: System.Console.WriteLine( "My hair color is {0}", myCharacter.HairColor);. Unnecessary string concatenation should be avoided when possible.

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.

Advertisement
Always nice to have big brother looking over my shoulder. [lol] I'll correct my post. [wink]
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
Thank you for the explenations, interfaces actually makes a lot more sense now. The signature of an interface cannot be changed, only the internal workings of the body scope for its derived method. The signature of a method defines the parameters as well as the return type and its name, gotcha.

Your example code for enums and properies makes it a lot easier to understand. The way I know arrays, they can be used similar to enums. What's the advantage in using enums instead of arrays? Personally, I think it looks a lot cleaner, and another advantage is probably the intellisense feature that's inside VS2005 so the values are suggested in a list. Is it much difference in performance?

Am I right that all values inside a enum is of type string?

If I wanted a flat based design for items like weapons et cetera, is storing it in enums within a sourcecode the usual way to go? Text files is probably a strong alternative, but that opens up the chance of user modification if the game where client based.

Sorry if some of these questions doesn't fit under the scope of our current week, but I'm really excited about the RPG game and I got thousands of game designs running through my head! :)
Quote: The signature of a method defines the parameters as well as the return type and its name, gotcha.


Well, sortof, not really. A method's signature consists of just its name and parameters. Not it's return type. This is so that when overloading a method, the compiler can tell a method apart by its name and parameter list. Two methods with the same name which only differ by return type is not accepted as overloading. For example.

class SampleClass{    public int DoSomething()    {        // ...    }	    // Error ... already contains a definition for 'DoSomething'	    public bool DoSomething()    {        // ...    }    // Accepted, as the parameter list is different    public int DoSomething(int param1)    {    }    // Also Accepted, as the parameter list is different    // Notice that because it's accepted as a unique method, I can ALSO    // change the return type.  But the key is the parameter list is different    public int DoSomething(int param1, int param2)    {    }}


However, in the case of overriding (note the difference between overriding, and overloading), both the name, parameter list, and return type must match in order for the compiler to believe that the derived class properly implements the interface. This is true for classes which inherit from a base class and not an interface as well. Just remember, a method's signature does not include it's return type. But when overriding, the method's signature and the return type must match.

Quote: Your example code for enums and properties makes it a lot easier to understand. The way I know arrays, they can be used similar to enums. What's the advantage in using enums instead of arrays?


Hrmm...Not quite. Enums are a method of creating symbolic constants which improve readability while also defining a new type. In the case of my previous example, I created a new type called HairColor, which allowed me to use constants such as HairColor.Auburn, HairColor.Black, etc...Once an enum has been defined, the values cannot be changed.

Arrays on the other hand, are a dynamic construct that allows the creation of sets of data. While it's possible, and common to create an array of strings, you still would not be able to use the strings at compile time as symbolic constants in the code. See the following example.

class Program{    static void Main(string[] args)    {	// Creates an array of strings (you must use an existing type, arrays do not create a new type	// I called the variable name HairColor to be consistent with my enum example        string[] HairColor = new string[]         {             "Brown",                   "Cinnamon",            "Black",                   "Blonde",            "Golden",                    "Auburn",            "Red",                    "Scarlet",            "White",            "Gray"                 };	// This is the correct way to use an array.  Since the array is of "String" type,	// I must assign its values to other strings.  Also, notice I use the indexer	// to get the 0'th element in the array.        String myString = HairColor[0];        // Error: System.Array does not contain a definition of 'Brown'	// You cannot refer to elements with array as members of the type, because arrays	// aren't types, simply collections of data        String myString = HairColor.Brown;        // Error: The type or namespace 'HairColor' could not be found	// Again, I did not create a type, I created a collection of variables OF a type ..	// in this case, String.        HairColor myColor = HairColor[0];    }}    


Quote: Am I right that all values inside a enum is of type string?

Actually, the values inside of an enum are NEVER of type 'string'. The values in an enum can be of any of the following underlying integer types:

byte, sbyte, short, ushort, int, uint, long, ulong

Interestingly enough, although the underlying type of an enum is always an integer type, outputting the value of an enum in a string will always give you the name of the value, as a string. This is an implicit conversion. If you want the value as an integer, you can do an explicit conversion. We'll cover this next week.
Quote:
If I wanted a flat based design for items like weapons et cetera, is storing it in enums within a source code the usual way to go? Text files is probably a strong alternative, but that opens up the chance of user modification if the game where client based.

Generally speaking you would create a class called "Weapon". The attributes (not the C# idea of attributes, but things like weapon type, damage, etc...) of the weapon would then be stored in the class as fields, with appropriate Properties to provide setters/getters. Then, the actual data for a weapon could be easily written out to, or read from a text file. At run-time, the values would be read from a file and "Weapon" objects would be created for each of your weapons loaded in the game. Now, it's important to note that this "text file" of weapon information can be made a resource of the application (beyond the scope of this workshop) which causes the text file to be compiled into the executable of the application, and unmodifiable by users.
Quote:
Sorry if some of these questions doesn't fit under the scope of our current week, but I'm really excited about the RPG game and I got thousands of game designs running through my head! :)

It's fine, ask all the questions you like. I, or someone else, will let you know if the questions are too advanced for the scope of this week or this workshop. I'm glad you're excited about the RPG. Continue to ask questions, and I apologize if I have to correct you. It's the only way to learn, however.

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
All the enums are of type enum. Enum is a structure that has some helpful functions to help you out.

If you want your enum to be a string you can also do an myEnum.ToString() to get out the string values. But remember there is also a number part of the enum structure.

Say we have a day of the week enum (sun - sat);

You can cast the day_of_week enum to an int and get the number value.

public enum day_of_week{     Sunday = 0,  // 0 is assumed if you don't put in a value.     Monday,     Tuesday,     Wednesday,     Thursday,     Friday,     Saturday}public string[] day_abbr = {sun, mon, tue, wen, thr, fri, sat};string current_day_abbr = day_abbr[(int)day_of_week];


theTroll
[/source]

This topic is closed to new replies.

Advertisement