patterncsharpMinor
Managing contacts
Viewed 0 times
contactsmanagingstackoverflow
Problem
I'm trying to tidy the following fragment of code:
But when I simplify it in the following way, I run into problems because I have to pass the objects by ref. And if I do that, then I get an error (A property, indexer or dynamic member access may not be passed as an out or ref):
Any ideas?
if (this.Details.Recipients.Count > 0)
this.Recipient = this.Details.Recipients[0];
else
{
this.Recipient = new Contact();
this.Details.Recipients.Add(this.Recipient);
}
if (this.Details.CCs.Count > 0)
this.CC = this.Details.CCs[0];
else
{
this.CC = new Contact();
this.Details.CCs.Add(this.CC);
}
if (this.Details.BCCs.Count > 0)
this.BCC = this.Details.BCCs[0];
else
{
this.BCC = new Contact();
this.Details.BCCs.Add(this.BCC);
}But when I simplify it in the following way, I run into problems because I have to pass the objects by ref. And if I do that, then I get an error (A property, indexer or dynamic member access may not be passed as an out or ref):
InitialiseContacts(this.Details.Recipients, this.Recipient);
InitialiseContacts(this.Details.CCs, this.CC);
InitialiseContacts(this.Details.BCCs, this.BCC);
}
static void InitialiseContacts(ObservableCollection contacts, Contact contact)
{
if (contacts.Count > 0)
contact = contacts[0];
else
{
contact = new Contact();
contacts.Add(contact);
}
}Any ideas?
Solution
So I think the error you is getting is hopefully obvious. You can't pass a property by ref. There is quite a few answers if you google this. Here's a quick one I found on stack overflow
So instead don't pass in the object, but rather have a new instance returned from the method. Something along the lines of
So instead don't pass in the object, but rather have a new instance returned from the method. Something along the lines of
this.BCC = FirstOrCreateIfEmpty(this.Details.BCCs);
this.CC = FirstOrCreateIfEmpty(this.Details.CCs);
public Contact FirstOrCreateIfEmpty(List contacts)
{
if(contacts.Any())
{
return contacts.First();
}
var contact = new Contact();
contacts.Add(contact);
return contact;
}Code Snippets
this.BCC = FirstOrCreateIfEmpty(this.Details.BCCs);
this.CC = FirstOrCreateIfEmpty(this.Details.CCs);
public Contact FirstOrCreateIfEmpty(List<Contact> contacts)
{
if(contacts.Any())
{
return contacts.First();
}
var contact = new Contact();
contacts.Add(contact);
return contact;
}Context
StackExchange Code Review Q#43580, answer score: 6
Revisions (0)
No revisions yet.