Link to home
Start Free TrialLog in
Avatar of aspnet-scotland
aspnet-scotlandFlag for United Kingdom of Great Britain and Northern Ireland

asked on

How do I return specific arguments in C#?

Hi,

I have an arguments class containing four args. Within a calling class I want to return only two of these args if possible, i.e.

WebsiteArgs myArgs = args as WebsiteArgs;
.
.
.
return (myArgs.argOne, myArgs.argTwo);

Using the above code I flag an error. I can use "return(myArgs);" but I don't want to return them all.

Thanks.
Avatar of Daniel Van Der Werken
Daniel Van Der Werken
Flag of United States of America image

I'm pretty sure you can't return two things at once this way.  You need to do a couple of things:

1.  Create an array and return that.  For example:

string [] myFunction( WebSiteArgs myArgs )
{
   string[] retArgs = new string[]{ myArgs.argOne, myArgs.argTwo };
   return retArgs;
}

of course, you would type it differently as needed.

The other way is to use like a Dictionary<type,type> and return that.  So,

Dictionary<int, int> myFunction( WebSiteArgs myArgs )
{
   Dictionary<int, int> myDict = new Dictionary<int,int>();
   myDict.Add( myArgs.argOne, myArga.ArgTwo );
   return retArgs;
}

There might be other ways, but those are two I can think of.  
Use the option "yield return" option will help to resolve your requirment

Please take a look into the MSDN link for more information

http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
You can only return one object from a function.

So you could have an object (class or struct) that has the 4 items as member of it.
Or you could pass objects into the function as ref - so you can modify the contents of them that way.
Group your 2 values into a structure and return the structure.

You could also have 2 parameters passed by reference to the function. If you fill those parameters with values in the function, the caller will be able to retrieve the values when coming back from the function. Lookup the ref keyword in the documentation. It is equivalent to ByRef in VB if you ever programmed in VB.

Of the 2, the first one would be considered better design however.
Avatar of aspnet-scotland

ASKER

Dan7el,

How would I add 3 args to a dictionary as when I attempt to do this I get method add has 2 parameters but is invoked with 3 arguments?

Thanks.
Avatar of MDUnicorn
MDUnicorn

The best way is:
return Tuple.Create(myArgs.argOne, myArgs.argTwo);

Open in new window

Remember that your method's return type should be: Tuple<ArgOneType,ArgTwoType>
For example if argOne is of type int and argTwo is of type string, your method looks like this:
Tuple<int,string> MyMethod()
{
[indent]
.
.
.
return Tuple.Create(myArgs.argOne, myArgs.argTwo); 
[/indent]
}

Open in new window

You can access your returned values like this:
var ret = MyMethod();
Console.WriteLine("{0}, {1}", ret.Item1, ret.Item2);

Open in new window


Tuple generic class is a simple class that can be used for simple data transfer between places in your code.
It has many variation with different number of parameters.
You can use it with from 1 to 8 parameters (Tuple<T1>, Tuple<T1,T2> ...). the static Tuple class, is a helper class for creating Tuple generics. It has 8 generic Create methods.

http://msdn.microsoft.com/en-us/library/system.tuple.aspx
http://msdn.microsoft.com/en-us/library/dd268536.aspx
MDUnicorn,

How would I implement the tuple if my class is inheriting from a base class and my return needs to come from a method that overrides an existing method from that base class?

Thanks.
You mean your method overrides a method from the base class and you cannot change your return type, right?
What is your return type? If you cannot change your return type, none of the above solutions work for you.
Can you post your method signature (return type and parameters)?
Return type is Object.

I'm trying to write a proxy operation (Args class and Op class, both attached below) for a sharepoint sandbox solution so I can send emails from my sandbox solution.


//*************Args

[Serializable]
    [Microsoft.SharePoint.Security.SharePointPermission(System.Security.Permissions.SecurityAction.LinkDemand, ObjectModel = true)]
    public class WebsiteBTEmailProxyOperationArgs : SPProxyOperationArgs
    {
        public WebsiteBTEmailProxyOperationArgs(string txtContactName, string txtEmailAddress, string txtPhone, string txtMessage)
        {
            this.BTEmailContactName = txtContactName;
            this.BTEmailAddress = txtEmailAddress;
            this.BTEmailPhoneNumber = txtPhone;
            this.BTEmailMessage = txtMessage;
        }

        public string BTEmailContactName { get; set; }
        public string BTEmailAddress { get; set; }
        public string BTEmailPhoneNumber { get; set; }
        public string BTEmailMessage { get; set; }
    }

//*************OP

[Microsoft.SharePoint.Security.SharePointPermission(System.Security.Permissions.SecurityAction.LinkDemand, ObjectModel = true)]
    public class GetWebsiteBTEmailProxyOp : SPProxyOperation
    {
        private Boolean SendEmail()
        {
            try
            {
                bool flag = false;
                SPSecurity.RunWithElevatedPrivileges(
                  delegate()
                  {
                      using (SPSite site = new SPSite(
                        SPContext.Current.Site.ID,
                        SPContext.Current.Site.Zone))
                      {
                          using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                          {
                              //flag = SPUtility.SendEmail(SPContext.Current.Web, messageHeader, message.ToString());

                              flag = SPUtility.SendEmail(web, true, true,
                                     "a@b.com",
                                     "Email",
                                     "This is a sample email Body");
                          }
                      }
                  });
                return flag;
            }
            catch (System.Exception exp)
            {
                // Do some error logging
                return false;
            }
        }
        
        public override object Execute(SPProxyOperationArgs args)
        {
            if (args != null)
            {
                WebsiteBTEmailProxyOperationArgs myArgs = args as WebsiteBTEmailProxyOperationArgs;

                // Build the email subject string
                StringBuilder subject = new StringBuilder();
                subject.Append("Contact Form Message from ");
                subject.Append(myArgs.BTEmailContactName);

                // Build the email message string
                StringBuilder message = new StringBuilder();
                message.Append("Contact Name: ");
                message.AppendLine(myArgs.BTEmailContactName);
                message.Append("Email Address: ");
                message.AppendLine(myArgs.BTEmailAddress);
                message.Append("Phone: ");
                message.AppendLine(myArgs.BTEmailPhoneNumber);
                message.AppendLine();
                message.AppendLine("Message:");
                message.AppendLine(myArgs.BTEmailMessage);

                // Construct the message header
                var messageHeader = new System.Collections.Specialized.StringDictionary();
                // TODO: Where to send the email
                messageHeader.Add("to", "a@b.com");
                // TODO: Who the email should be "from"
                messageHeader.Add("from", "a@b.com");
                messageHeader.Add("subject", subject.ToString());
                messageHeader.Add("content-type", "text/plain");

                // Send the email
                SPSecurity.RunWithElevatedPrivileges(delegate
                                                          {
                                                              SPUtility.SendEmail(SPContext.Current.Web, messageHeader, message.ToString());
                                                          });
                
                
                return myArgs;
            }
            return null;
        }
    }

Open in new window

So you want to return some of the values of myArgs in Execute method, right?
Because return type of Execute method is object, you cant return anything you want. So you can easily wirte:
return Tuple.Create(myArgs.argOne, myArgs.argTwo);

Open in new window

and you must be careful about the method usage. Anyone that calls this method, should know that you are returning a Tuple<T1,T2>, and cast the return value to that.

But, why do you need it? Why do you want to return only some of the values? You can create a new WebsiteBTEmailProxyOperationArgs, and only fill the required properties (leave others as null).
There is no overhead for this, because you are returning a reference to an object, and it doesn't matter how many properties that object contains.
I actually want to return them all but as their full reference, i.e. myArgs.argOne, myArgs.argTwo etc. When I try to return myArgs all that returns is the actual class name?

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of MDUnicorn
MDUnicorn

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial