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).
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
}
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With