Passing a Property

  • Thread starter Thread starter bill
  • Start date Start date
B

bill

Hi

I'd like to pass a property (say like a row value from a typed dataset) to a
method so that the method can get/set the property. for instance

DoSomething(ATypedRow.StringField)

where "StringField" is a string property on a typed row.

however, DoSomething requires a string argument in this case

private void DoSomething(string aField)
{
aField = "new stuff"; // throws exception
}

Any ideas?

thanks

bill
 
Bill,

Since a property is in essence a method that is called, you need to pass
the object that exposes the property and then set the property from inside
the method.

I think that a better solution would be to have the method return the
value somehow (returning, or through a ref/out parameter), and then set the
property outside of the method.

Hope this helps.
 
Well, here is what is happening. I have a typed dataset with a lot of
fields. Most of them are strings. I am passing info back from a form that
has to fill the typed row. OK. I want to set the field to the value in a
control unless it is blank. so what I have is about fifty

if(c_MyFirstName.Text.Lenth > 0)
{
aRow.MyFirstName = c_MyFirstName.Text)
}

clauses. so I thought I could have a method to shorten this repetitive
action up

AssignStringToRow(string aInput, some_type aProperty)

where the above code could be generic

if(aInput.Length > 0)
{
aProperty = aInput;
}

then I'd have a bunch of

AssignStringToRow(c_MyFirstName.Text, aRow.MyFirstName);

if I pass the row in, I don't know what field to assign unless I pass a
string or index in and then the battle is lost as far a type safety. also
if I return a value, I will set the row value to something every time as in

aRow.MayFirstName = AssignStringToRow(c_MyFirstName.Text);

what happens when input string is blank? do I return a null? I don't think
so. You have to use SetMyFirstNameNull() to do that. Else I could assign
blank strings? It just seems a waste, or ugly, or something. I'd rather
have the "if" clauses.


bill


Nicholas Paldino said:
Bill,

Since a property is in essence a method that is called, you need to pass
the object that exposes the property and then set the property from inside
the method.

I think that a better solution would be to have the method return the
value somehow (returning, or through a ref/out parameter), and then set the
property outside of the method.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

bill said:
Hi

I'd like to pass a property (say like a row value from a typed dataset)
to
a
method so that the method can get/set the property. for instance

DoSomething(ATypedRow.StringField)

where "StringField" is a string property on a typed row.

however, DoSomething requires a string argument in this case

private void DoSomething(string aField)
{
aField = "new stuff"; // throws exception
}

Any ideas?

thanks

bill
 
Back
Top