views:

842

answers:

6

Hello,

I know this is a dumb question and I guess it must have been asked before. However I am unable to find an answer to my question.

Here is some sample code (which of course does not compile) to outline my problem:

class test
{
     int[] val1;
     string val2;

     static bool somefunction(test x, test y)
     {
         dosomestuff()

         test result;

         while(result is nothing)
         {
              if(somecondition){result=new test(something);}
         }
     }
}

The problem which I have is in the following line:

while(result is nothing)

This is the syntax from VB, which of course is not what the C# compiler accepts. Could somebody tell me how to resolve the problem?

Thanks for your help, Niklas Fischer

+4  A: 
while (result == null)
Robert Harvey
The compiler throws the following exception for that:"Use of the unassigned local variable 'test'"
niklasfi
That's a different line of code.
Robert Harvey
No, since I did not as Colin Mackay suggested set test=null in the first place.
niklasfi
OK. Glad you were able to figure it out.
Robert Harvey
1+ for the effort
niklasfi
+2  A: 
while (result ==null )

if that's what you mean

satyajit
+1  A: 
while(result == null)

The equivalent of nothing in C# is null.

Supertux
+11  A: 

The syntax you are looking for is:

while (result == null)

You also have to set result = null; to start with also

Colin Mackay
A: 
while (result == null)
djangofan
+1  A: 

Although you have an answer you're happy with, there's something behind this you may find interesting or helpful.

There is a difference between C# and VB.NET. In VB.NET you can write:

Dim b as Boolean

And in C# you can write:

bool b;

They are subtly different. In VB.NET, b has been given the value false (in other words, it has already been initialized). In C#, b has no value (it is uninitialized). C# goes to a lot of effort to make sure you cannot examine the value of a variable that has never been initialized.

So you are not testing whether the variable is initialized. In VB.NET there is no such thing as an uninitialized variable. In C# it is impossible to get the value of an uninitialized variable in order to compare it with anything.

You're testing whether the variable has been initialized to null or Nothing.

Daniel Earwicker