Dictionaries, Classes and Properties  
Author Message
Jonanin





PostPosted: Visual C# Language, Dictionaries, Classes and Properties Top

Hello,

I am actually using the XNA framework for this app, but this question doesn't really relate to XNA all that much, more just the C# language.

I have a dictionary array containing instances of my Sprite class. My sprite class has a position property, which is a Vector2. I use get, and set with my property of course. Now, i get an error when I try to do this:

sprites["mysprite"].Position.X = 100;

yet, it is fine when I do this:

sprites["mysprite"].Position = Vector2.Zero;

The error is:
Error 1 Cannot modify the return value of 'Disasteroid.Sprite.Position' because it is not a variable

Can I get and set child properties of my position property I have seen code snippets that do this.

Here is my code:
I have a dictionary array called sprites, using a string as key and a Sprite as the value (Sprite is a class):

Dictionary<string, Sprite> sprites;

Now, here is my little Sprite class:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Disasteroid
{
class Sprite
{
private Texture2D SpriteTexture;
private Vector2 SpritePosition;
private Color SpriteColor;

public Sprite(Texture2D STexture, Vector2 SPosition, Color SColor)
{
this.SpriteTexture = STexture;
this.SpritePosition = SPosition;
this.SpriteColor = SColor;
this.Texture = STexture;
this.Position = SPosition;
this.Color = SColor;
}

#region Properties (texture, position, color)

public Texture2D Texture
{
get { return SpriteTexture; }
set { SpriteTexture = value; }
}

public Vector2 Position
{
get { return SpritePosition; }
set { SpritePosition = value; }
}

public Color Color
{
get { return SpriteColor; }
set { SpriteColor = value; }
}


#endregion


}
}

and here is how i add a Sprite to my sprites variable:

protected void NewSprite(string name, string path, Vector2 position, Color color)
{
sprites[name] = new Sprite(textures[name], position, color);
}

I know some of it has to do with XNA but I feel that is not where the problem lies.

Why doesn't it work I thought this should work, aren't you able to set and get child properties of a property


Visual C#6  
 
 
Mattias Sjogren





PostPosted: Visual C# Language, Dictionaries, Classes and Properties Top


Why doesn't it work I thought this should work, aren't you able to set and get child properties of a property

Not when the property returns a value type. The reason is that you get a copy of the value, and changing that wouldn't affect the original instance anyway.