Urgent: how to create Nested/Inner Property in CSharp

  • Thread starter Thread starter JollyK
  • Start date Start date
J

JollyK

Hello folks,

Suppose I have a property called SortField

string SortField
{
get
{
if (SortField == string.Empty)
{
return "123";
}
return SortField;
}
set
{
SortField == value;
}
}

Now I want to have a nested property like "SortField.SomePropertyName" . How
do I do this. Can u help with a sameple code. Thanks alot.
 
I think SortField would have to become a structure or class, and you would
have to have a property exposing an instance of this struct or class.
SortField would then have other properties.
 
JollyK said:
Suppose I have a property called SortField

string SortField
{
get
{
if (SortField == string.Empty)
{
return "123";
}
return SortField;
}
set
{
SortField == value;
}
}

Firstly, there's a problem with the above - you'll get a stack
overflow, because your property would just keep calling itself. You
need a variable there, and use that in your get/set parts.
Now I want to have a nested property like "SortField.SomePropertyName" . How
do I do this. Can u help with a sameple code. Thanks alot.

You can't - there's no such thing as a nested property. What exactly
are you really after?
 
Normally you use a Property to get or set a protected Field.

string protected sp_SortField=String.Empty;
string public s_SortField
{
get
{
if (sp_SortField == String.Empty
return "123";
else
return sp_SortField;
}
set
{
if (value == StringEmpty)
sp_SortField = "123";
else
sp_SortField = value;
}
)

Normaly "get" is only used for returning the sp_SortField, but such a
condition should work.
It would be better if sp_SortField is set to a valid value from the
beginning.
In you example : if (SortField == string.Empty)
- when comparing SortField you are calling get, which again calls get etc.
Also a loop!
// Now I want to have a nested property like "SortField.SomePropertyName"
not quite sure what you mean by this. SortField is allready nested as it is,
which is bad.

Hope this helps
Mark Johnson, Berlin Germany
(e-mail address removed)
 
Mark Johnson said:
Normally you use a Property to get or set a protected Field.

I don't. If there's a field involved, it's always private as far as I'm
concerned (for production code, at least)...
 
Back
Top