vicdotexe vicdotexe - 11 months ago 43
C# Question

Is there a more correct way to achieve what I'm doing?

I'm pretty new to C# and coding, so forgive my ignorance. I've tried researching and it seems like what I'm trying to find is possibly something called a "pointer" in C++, but not available in C#? I want a field or property which I can assign an object from a list as a "selected object" and play around with until I "release" it. I've tried this:

Entity GrabbedEntity;

List<Entity> Entities;

if (mouseDown)
GrabbedEntity = Entities[3];

if (mouseUp)
GrabbedEntity = null;

What I'm trying to achieve is basically just releasing the object I assigned to "grabbedEntity", and not actually making "Entities[3]" a null value, I still want to be able to modify the values of grabbedEntity though(mouseDown and =Entities[3] is for simplicity sake, it could be any object in list depending on circumstances). How I've been been working around it is this:

List<Entity> Entities;

List<Entity> _grabbedEntityList = new List<Entity>();
Entity GrabbedEntity
if (_grabbedEntityList.Count < 1) return null;
else return _grabbedEntityList[0];
if (value == null) _grabbedEntityList.Clear();

This works exactly as I intend it to, I can Assign "GrabbedEntity" to an object in my "Entities" list, while it's assigned I can do whatever I want to it, and then if I want to release it I just set it to null, but I feel like I'm making a work around for something that actually already exists. Thanks for any responses.

Answer Source

Your first approach should work just fine.

You say "How I've been been working around it is this:" but you failed to tell us what it is that you feel you need to work around. If you are concerned that GrabbedEntity = null; might set Entities[3]; to null, well, it won't, and if you have actually tried this, you should know that it doesn't.

As for the second approach, the one with the get{} and set{}, I have no idea what you are trying to do, nor how this convoluted mess is meant to accomplish it.