views:

108

answers:

1

I have a problem. When I run my program, it comes up with an error, specifically the CS1023 error. I guess it's because I have a declaration inside a statement, but I don't know how else to write the code. Sometimes C# annoys me, because in C++ I could get away with similar things... anyway, here's the code. I would appreciate it if somebody could explain it to me. Error Message Link

void BtnTotalSeasonsClick(object sender, EventArgs e)
{
    using (var stream = new FileStream(drvFile, FileMode.Open, FileAccess.ReadWrite)) 
    Byte[] bytes = System.Text.ASCIIEncoding.GetBytes(txtTotalSeasons.Text);
    {
        stream.Position = 4;
        Stream.WriteByte(0xCD);
    }
}

Fixed Code with CS0120 error.

        {
using (var stream = new FileStream(drvFile, FileMode.Open, FileAccess.ReadWrite))  
{ 
Byte[] bytes = System.Text.ASCIIEncoding.GetBytes(txtTotalSeasons.Text); 
stream.Position = 4; 
Stream.WriteByte(0xCD); 
} 
    }
+2  A: 

There's nothing apparently wrong with the code you pasted in. Perhaps the error is somewhere else above this, and the compiler is getting confused?

Ah, I see you've changed the code.

The problem here is you are declaring the Byte[] array outside the intended using block. Since the scope of the declaration as is is only one line, this constitutes a logic error, and the compiler catches it with a compile-time error.

The compiler is interpreting your code like this:

using (var stream = new FileStream(drvFile, FileMode.Open, FileAccess.ReadWrite))  
{ 
    Byte[] bytes = System.Text.ASCIIEncoding.GetBytes(txtTotalSeasons.Text); 
}

{        
    stream.Position = 4; 
    stream.WriteByte(0xCD); 
}

To fix it, move the Byte[] inside the braces, or outside the using block:

using (var stream = new FileStream(drvFile, FileMode.Open, FileAccess.ReadWrite))  
{ 
    Byte[] bytes = System.Text.ASCIIEncoding.GetBytes(txtTotalSeasons.Text); 
    stream.Position = 4; 
    stream.WriteByte(0xCD); 
} 

-or-

Byte[] bytes = System.Text.ASCIIEncoding.GetBytes(txtTotalSeasons.Text); 

using (var stream = new FileStream(drvFile, FileMode.Open, FileAccess.ReadWrite))  
{ 
    stream.Position = 4; 
    stream.WriteByte(0xCD); 
} 

Personally, I like being annoyed by the compiler here, since it saves me from a run-time error.

codekaizen
Thanks, that fixed it. Now another error (CS0120) has come up, so I'll fix that. Thanks though.
JC Leyba
Instance method call needs an instance? We can help with that, here, too!
codekaizen
Well, could you help with that also? I get two errors, one in the 4th. line of code above, and one in the 6th, both being CS0120 errors.
JC Leyba
"Stream.WriteByte(0xCD);" - needs to be "stream.WriteByte(0xCD);" C# is case sensitive, and "Stream" refers to the class, not the object, which is "stream".
codekaizen