Structs + Object

  • Thread starter Thread starter Jon Skeet [C# MVP]
  • Start date Start date
J

Jon Skeet [C# MVP]

Tamir Khason said:
Little question:
I have a class A
{
public A()
{
//Whatever
}
public SomeStruct prop
{
get {return m_prop;}
set {m_prop = value;}
}
}
And structure SomeStruct
{
public string s1,s2;
public SomeStruct(string a1, a2)
{
s1 = a1;
s2 = a2;
}
}

I want to be able to assign A.prop.s1 = "Whatever"; and A.prop.s2 =
"Whatever 2"; //unable to modify rerurn value, but I want to !!!
rather then A.prop = new SomeStruct("Whatever","Whatever 2");

How to do this, ideas?

Well, you just can't, with the above. You could:

1) Have methods in A to set each part part of the property
2) Make SomeStruct a class instead
3) (Not recommended) Make m_prop public, and get rid of the property
 
Little question:
I have a class A
{
public A()
{
//Whatever
}
public SomeStruct prop
{
get {return m_prop;}
set {m_prop = value;}
}
}
And structure SomeStruct
{
public string s1,s2;
public SomeStruct(string a1, a2)
{
s1 = a1;
s2 = a2;
}
}

I want to be able to assign A.prop.s1 = "Whatever"; and A.prop.s2 =
"Whatever 2"; //unable to modify rerurn value, but I want to !!!
rather then A.prop = new SomeStruct("Whatever","Whatever 2");

How to do this, ideas?

TNX
 
tnx
If I'll do it class so what'll happend with initialization? This way I'd
have to initialize it each time used or do it something like
public SomeClass
{
public string s1,s2;
}

....

--
Tamir Khason
You want dot.NET? Just ask:
"Please, www.dotnet.us "
 
Tamir Khason said:
If I'll do it class so what'll happend with initialization? This way I'd
have to initialize it each time used or do it something like
public SomeClass
{
public string s1,s2;
}

No, you specify a constructor with the class, just as you did with the
struct.
 
Hi Tamir,

First of all, I would like to confirm my understanding of your issue. From
your description, I understand that you are receiving a compiler error when
assigning to a property returned value. If there is any misunderstanding,
please feel free to let me know.

You get this error because SomeStruct is a value type. When the property
returns it, it is put on the stack as a temporary variable. It is a copy of
m_prop and is read-only. Assigning value to it doesn't make sense. If you
need to assign to it, besides make SomeStruct a class, you can also try the
following when accessing it.

SomeStruct ss = a.prop;
ss.s1 = "Whatever";

HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 
Back
Top