2

I recently switched over from C++ to C# and I am wondering how I would do the equivalent in c#. In C++ I could have done this:

Enemy *enemy; 

enemy = new Enemy("Goblin", 20, 20); 

In c#, I tried the pointer methond and using a delegate and both failed. The thing is I have multiple enemys in my Text RPG and I need to assign a specific enemy to my enemy pointer class so I then can preform the battle processes.

1 Answer 1

4

C# has references instead of C++ style pointers. So for your example, you would just do:

Enemy enemy; //enemy is a reference to an Enemy
enemy = new Enemy("Goblin", 20, 20); //the reference points to a Enemy instance in the heap

Another interesting difference is that almost everything is a reference, apart from some primitive value types (int, float, double, decimal, bool, structs, enumerations) which can be stored on the stack.

Sign up to request clarification or add additional context in comments.

5 Comments

As a side note you CAN use pointers, however they are considered unsafe and you have to mark your code as such - msdn.microsoft.com/en-us/library/t2yzs44b(v=vs.80).aspx
Value types are only stored on the stack when they are local variables, otherwise they are part of an object which is stored on the heap.
@user2097371 ipavlic's sample works because in C# classes are passed by reference, not by value. An excelent article to understand this relationship is this one about the difference between Class and Struct in C# geekswithblogs.net/BlackRabbitCoder/archive/2010/07/29/…
@EtherDragon: No, references are not passed by reference unless you use the ref keyword. Passing a reference and passing by reference is two different things.
Thanks, I didn't think it would be that simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.