Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing in an object as an out parameter

Tags:

c#

reference

I have a method that checks for validity of an object with respect to my program (some algorithm). The object is created(parsed) from a string that is passed in.

The logic is:

 bool isValid(String str, out Object obj)
    {
         obj = null;
         obj = new Object(str); //Validation happens during the object creating
         if(obj.Legit) //Don't mind this line :)
             return true;
         return false;
    }

And I call this validation from another class, which if this validation fails, does a different validation (same method)

void FindingObjectType(String str)
{
        if(isValid(str, out ??????)
             //process
}

So instead of ?????, I don't know how to pass the object.

I have only 1 constructor, Object(String).

like image 605
Alexey Avatar asked May 03 '13 18:05

Alexey


3 Answers

This MSDN document describes the "out" keyword:
http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx

Before you call the isValid() method, you need to declare the output object:

void FindingObjectType(String str)
{
    Object obj;
    if(isValid(str, out obj)
         //process
}
like image 113
nic Avatar answered Oct 01 '22 22:10

nic


As nic said, typically you would say:

void FindingObjectType(String str)
{
    object obj;
    if(isValid(str, out obj)
    {
         // process valid obj
    }
}

That's perfectly acceptable. However, there are other ways you could do this that are possibly better:

Thing GetThing(String str)
{
     Thing thing = new Thing(str);
     if(thing.Legit)
         return thing;
     return null;
}

void FindingObjectType(String str)
{
    Thing thing = GetThing();
    if(thing != null)
         //process
}

Here's another:

Thing GetThing(String str)
{
     // Make a static method that tests the string.
     if (Thing.IsLegit(str)) 
         return new Thing(str);
     return null;
}

void FindingObjectType(String str)
{
    Thing thing = GetThing();
    if(thing != null)
         //process
}

Of course if you are going to do that then why do you need GetThing? Just say:

void FindingObjectType(String str)
{
     if (Thing.IsLegit(str)) 
     {
         Thing thing = new Thing(str);
         //process
     }
}

This last pattern is probably the best. You want to separate your concerns. When you have an out parameter it is usually because the method is trying to do too many things.

like image 35
Eric Lippert Avatar answered Oct 02 '22 00:10

Eric Lippert


You just need to declare an object. The below code will work for you.

void FindingObjectType(String str)
{
        Object obj;
        if(isValid(str, out obj)
             //process
}
like image 35
Vinay Avatar answered Oct 02 '22 00:10

Vinay