Jojo Jonas
Jojo Jonas

Reputation: 223

Visual Studio C# Ignore an Error

Is there a way in C# that I can signal to VS to force it to ignore an error on a specific line?

I have a variable, pos2, that is only initialized some of the time (it's random). However, when it is initialized, I set a flag at the same time.

pos2 = new Vector3(2.5F, 0.624F, 75F);
secondCar = true;

Later on in the code (behind my flag check), I use pos2 normally, and the editor throws an error. I use this script regularly, so I know it's not broken, and since pos2 is behind the flag check, I know I will never reach a point where pos2 is used when undeclared.

In Python, you can use "@UnusedVariable" or something like that (I don't remember exactly), but my VS editor keeps on throwing me an error for this, and I know that it will never reach this situation.

Upvotes: 2

Views: 2734

Answers (4)

Servy
Servy

Reputation: 203850

You want to initialize the variable to null or some other default value. That way the error will go away, rather than just being suppressed.

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100630

Consider using Vector3? (nullable type) instead of Vector3 as there is no way to suppress the error.

Upvotes: 3

Katie Kilian
Katie Kilian

Reputation: 6993

See this answer for more details, but generally, you can use #pragma warning disable to disable warnings.

... I assume you do mean warnings, right? If it is an error, your code won't compile, so you can't ignore that. But you can ignore warnings. If you are really getting an error, just use a variable initializer, like this:

int someVariable = 0;
YourClass someInstance = null;

Then the compiler won't complain about uninitialized variables.

Upvotes: 0

JaredPar
JaredPar

Reputation: 755557

It sounds like you are getting as CS165 error about the use of an unassigned local variable. Simply put there is no way to suppress this message. Warnings in C# are suppressible but errors are not.

Today the code may indeed be correct and the uses properly predicated on appropriate gates like the secondCar you mentioned. However these logic gates may not be obvious to the next developer or even yourself a week or so from now. Attempting to suppress a valid error like this in C# is just opening the gate for future problems down the road.

Instead of trying to fight the compiler here I would recommend working with it instead.

Upvotes: 3

Related Questions