Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CS0219 or new warning for unused variable when language version supports discard #2782

@binki

binki commented Sep 5, 2019

:

class C { public void M(IThing thing) { var needUpdateVariable = thing.Something; } public interface IThing { object Something { get; } } }

:

class C { public void M() { var needUpdateVariable = 0; } }

Now that the exists, there is no need to treat the first case any differently than the second. However, changing code to be warningful that wasn’t before is breaking. So, there should be a new warning which will report assigned-but-never-used-variables like in the first example which can be rewritten like:

class C { public void M(IThing thing) { _ = thing.Something; } public interface IThing { object Something { get; } } }

The point of the warning would be to give the developer the opportunity to research whether or not evaluating the RHS of the declaration is actually necessary. For example, using a discard like above makes it obvious that the getter has a side-effect (eww!). Or, as the example for discards shows, you might call a method which returns a which you intentionally decided not to for some reason. Or, the variable declaration may have been entirely superfluous and can be removed. In all of these cases, I would appreciate the compiler’s help with a warning to clean my code of declared-and-assigned-but-never-read variables (beyond what CS0219 gets you).

@Scott-Caldwell

Scott-Caldwell commented Sep 5, 2019

If you're using an IDE that supports files, you can already accomplish this with the unused value preference settings.

Reference:

Sorry, something went wrong.

binki commented Sep 6, 2019

No, that does something different. Turning on forces me to insert a bunch of discards or local variables that I previously didn’t need. It also has no “don’t assign the result to anything” option (at least that I see in the documentation).

What I am trying to do is convert to discards the local variables that were created to

The option you gave me causes the compiler to force me to start using discards for all unused expressions. That means adding discards where neither of the two above issues originally required me to assign the value to something. I.e., turning that on forces me to add code.

I get the purpose of the rule. Such a rule would make sense if one wanted their code to observe/handle the return values of all methods. However, there are a lot of methods whose return value I don’t care about. For example, when I want to use if the input string is unparsable. Right now, at least, I am not convinced that I would want to be forced to discards to my code all over the place. I want the compiler to help me unread locals (giving me an opportunity to either replace the variable with a discard or remove the entire statement/RHS altogether).

Scott-Caldwell commented Sep 6, 2019

There are actually two different settings in my link, and it seems like you just stopped at the first one.

The second setting ( ) tells the IDE how to behave when you try to assign something to an otherwise unused variable, which, now that you've clarified your intent more, sounds like what you want.

So if you had :

GetInt32OrDefault1(string str) { // Warning: Unnecessary assignment of a value to 'unused' // Visual Studio offers a code fix to add a discard var unused = int.TryParse(str, out var result); return result; } int GetInt32OrDefault2(string str) { int.TryParse(str, out var result); // No warning return result; }

binki commented Sep 10, 2019

:

GetInt32OrDefault1(string str) { // Warning: Unnecessary assignment of a value to 'unused' // Visual Studio offers a code fix to add a discard var unused = int.TryParse(str, out var result); return result; }

This is not quite exactly what I want. I want the codefix to be to remove the variable, not to use a discard. I only want the codefix to be to use a discard if that is necessary to:

GetInt32OrDefault2(string str) { int.TryParse(str, out var result); // No warning return result; }

But there still is an IDE0058 diagnostic and codefix for adding a discard—unless I replace with . But that is insufficient to address the issue. There’s a missing option for to remove the discard if it isn’t needed. It should be possible to have the following be a codefix to remove the discard:

GetInt32OrDefault3(string str) { _ = int.TryParse(str, out var result); return result; }

For the following to have a codefix to remove the unused variable (without replacing it with a discard):

GetInt32OrDefault4(string str) { var unused = int.TryParse(str, out var result); return result; }

And at the same time have a codefix to replace the unused variable with a discard in the following (because removing it would result in ):

Task DoSomethingAsync5() { var ignored = StartSomeBackgroundProcessWeKindOfDoNotCareAboutAsync(); }

And also be able to have a codefix replace the unused variable with a discard when invoking a getter with side-effects:

DoSomething6() { var unused = blah.QuestionableProperty; }

In my understanding, to do this, there would need to be something like these imaginary settings. The thing is, these are imaginary—they don’t exist.

.cs] # Would need a new codefix option “leave_unused” so that code generation does not emit a discard or variable. csharp_style_unused_value_expression_statement_preference = leave_unused:warning # Would need a new option which applies only to Task expressions to allow discard to be used when suppressing CS4014 csharp_style_unused_value_expression_task_statement_preference = discard_variable:warning # Would need a new option which only applies to getter invocations which requires an assignment operator csharp_style_unused_value_expression_getter_statement_preference = discard_variable:warning # Would need a new codefix option “remove_lhs_and_operator” or something so that both discard and unused variable can be removed via a codefix csharp_style_unused_value_assignment_preference = remove_lhs_and_operator:warning

I hope that clarifies what I am trying to accomplish and demonstrates how the existing options are insufficient for my use case.

Thanks for the followup!

Scott-Caldwell commented Sep 11, 2019

Adding some additional configuration options for .editorconfig files to support your code style sounds like a reasonable request. Probably more of a feature, though.

@daiplusplus

daiplusplus commented Oct 13, 2020 • edited Loading

(With apologies for the thread necromancy - I found this thread looking for info on some editorconfig options and it's currently 2:30am )

I feel all 4 of these are not ideal because if fails the value of be undefined, not . While in the case of specifically the to be set to when the parse fails, in other cases in other libraries (especially those without documentation) we should avoid .

In my code, I do this:

Or better yet:

Both of these have the benefit of not triggering any warnings because no value is ignored or discarded, it's self-documenting: it doesn't require anyone looking at the source of to open the documentation for to find out what value will have if returns false.

Unrelated-but-related, I also use this expression style, since C# allows a local variable declaration to be referenced in its own initializer:

@333fred

333fred commented Oct 13, 2020

The results of TryParse are absolutely well-defined:

__

Generally, all out parameters must be actually assigned by a method. Unless you use unsafe tricks, you can't skip assigning them with some value.

@HaloFour

HaloFour commented Oct 13, 2020

Or call a method in a VB.NET assembly. 😉

  • 👀 2 reactions

daiplusplus commented Oct 14, 2020 • edited Loading

Correct, they must be well-defined as far as the CLR/CLI is concerned, but I meant "well-defined" in a documentation/API-design sense: : "if returns the parameter's value is undefined" - so it be set to or . I just don't think it's wise to always assume that every method in in every library from every author will always set the value to in event of failure.

A good example is . (Note that it predates the pattern). You'd maybe expect that would return if it can't find a value, so you might check , but - so the check should be instead - I wonder how many people have been stung by that because of an they made about the nature of the output/return value.

(Another favourite is when an implementation returns between two values instead of only , , . A neat trick when implementing is to just do ).

Also this is yet another example of why C# code-contracts to come back.

HaloFour commented Oct 14, 2020

The compiler isn't assuming that the parameter is assigned to , it's assuming that the parameter has been assigned, which is a fairly safe bet. The compiler doesn't recognize that there is a relationship between the parameters and any other parameter, or the return value.

daiplusplus commented Oct 14, 2020

Yes, but I'm not talking about the compiler, I'm talking about the programmer writing the code making assumptions without having looked at the documentation, that's all.

333fred commented Oct 14, 2020

I don't see how code contracts would help at all with your example of binary search. Also, I don't believe that people will expect that binary search definitely returns -1; after all, you could well be finding where you need to insert into a list next (that's certainly how I use it most often). Nor would it help with : what kind of contract could you enforce? The result can be any , there's nothing else the compiler could say. The only thing that could actually help there is encoding some form of a linear type system into C#, and then actually have exhaustiveness-checking on the results in said type system.

Regardless, this is getting off the original topic on this issue. We could certainly consider more analyzer options for when things need to be discarded or not, but that is an issue for dotnet/roslyn, not for this repo. As such, I'm closing this out.

@333fred

No branches or pull requests

@binki

Unnecessary assignment of value to 'definedVariable'

In Visual Studio, I have seen this message in a few of the exercises I have worked on.. Where the variable is initialized to 0 or empty...etc... and then I use it to have values assigned to that variable via a method. I see the variable grayed out on the initialization, with the following message "Unnecessary assignment of value to 'definedVariable'" It's suggested fix is to replace the variable with an underscore. eg. (only a sample) int x = 0; x = GetFactor(a); suggested change to int x = 0; _ = GetFactor(a); It doesn't throw a compiler error and it's not even really a warning... I do think it is kind of annoying... I don't change it because I want the clarity and I want to insure the variable is initialized with 0 or empty. vs having int x = GetFactor(a); Why is VS giving this suggestion? Is there a precedence that I am missing?

Tibor Santa - avatar

Often have questions like this?

Learn more efficiently, for free:

unnecessary assignment of value c#

Introduction to Python

7.1M learners

unnecessary assignment of value c#

Introduction to Java

4.7M learners

unnecessary assignment of value c#

Introduction to C

1.5M learners

unnecessary assignment of value c#

Introduction to HTML

7.5M learners

Get the Reddit app

All about the object-oriented programming language C#.

The JIT compiler is using unnecessary assignment of a value.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

net core error unnecessary assignment of a value

see the code

here i am storing oResponseContext.ResponseData as DataTable into variable dt which is also a DataTable . so what is wrong for which i am getting Warning

if i rewrite the code this way

if i rewrite this line this way _ = oResponseContext.ResponseData as DataTable; then warning goes off.

i want to store oResponseContext.ResponseData as DataTable into variable dt . so if i use _ then how could i store value into dt ?

please guide me how to store oResponseContext.ResponseData into variable dt datatable without any warning? thanks

1 additional answer

Usually it does not have sense to assign a value to a variable if it is not used.

  • Mark Forums Read
  • Today's Posts
  • View Site Leaders
  • What's New?
  • Advanced Search
by clicking the link above. You may have to before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below. PowerPoster --> PowerPoster --> | Posting Permissions post new threads post replies post attachments edit your posts is are code is code is





 alt=

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

IDE0059 Unnecessary assignment of a value to 'result'

I get a message: IDE0059 Unnecessary assignment of a value to 'result'

How can I solve this problem?

  • compiler-warnings

Mureinik's user avatar

  • 1 Simple as: Employee result; . You always assign something to result –  Camilo Terevinto Commented Sep 20, 2020 at 13:39

Both branches of the if and the else assign a value to result , so you don't need to initialize it with null . This null is never read and will just be overwritten anyway.

  • 1 ... and unnecesary assignments can hide errors when you for instance later change that if/else. –  Henk Holterman Commented Sep 20, 2020 at 15:33

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c# blazor compiler-warnings or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • What could explain that small planes near an airport are perceived as harassing homeowners?
  • Can I get a refund for ICE due to cancelled regional bus service?
  • Geometry question about a six-pack of beer
  • add an apostrophe to equation number having a distant scope
  • Sangaku problem involving eight circles
  • Summation not returning a timely result
  • Does it matter if a fuse is on a positive or negative voltage?
  • Why potential energy is not considered in the internal energy of diatomic molecules?
  • Where can I access records of the 1947 Superman copyright trial?
  • How can a landlord receive rent in cash using western union
  • Was Paul's Washing in Acts 9:18 a Ritual Purification Rather Than a Christian Baptism?
  • How to produce this table: Probability datatable with multirow
  • How is Victor Timely a variant of He Who Remains in the 19th century?
  • Are there paintings with Adam and Eve in paradise with the snake with legs?
  • Is there any other reason to stockpile minerals aside preparing for war?
  • Matryoshka doll problem
  • Were there engineers in airship nacelles, and why were they there?
  • Do I need to indicate 'solo' for wind/brass instruments in shared staff?
  • What is the translation of misgendering in French?
  • Is it consistent with ZFC that the real line is approachable by sets with no accumulation points?
  • What is the term for when a hyperlink maliciously opens different URL from URL displayed when hovered over?
  • What to do if you disagree with a juror during master's thesis defense?
  • What happens to ARP replies if a switch connects to a router directly over one interface and indirectly over another?
  • Is it better to show fake sympathy to maintain a good atmosphere?

unnecessary assignment of value c#

COMMENTS

  1. c#

    Avoid unnecessary value assignments in your code, as these likely indicate redundant value computations. If the value computation is not redundant and you intend to retain the assignment, then change the assignment target to a local variable whose name starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc.

  2. Unecessary assignment of a value c# when using out

    4. Just don't set the initial value. This is perfectly valid code : string errorMessage; var valid = IsValid(out errorMessage); Or use. var valid=IsValid(out var errorMessage); The compiler knows that the variable is used as an out parameter and will get a value unless an exception is thrown. On the other hand, IsValid has to store a value in ...

  3. IDE0059

    C#. Copy. // IDE0059: value written to 'v' is never // read, so assignment to 'v' is unnecessary. int v = Compute(); v = Compute2(); You can take one of the following actions to fix this violation: If the expression on the right side of the assignment has no side effects, remove the expression or the entire assignment statement.

  4. How to understand C# warning IDE0059: "Unecessary assignment"

    as there is no code that uses the value wstr is set to, there is no point in setting a value to it. if you removed the unneeded assignments, you would get a warning about an unused variable. your code snippet could be simplified to: Copy. public void testmylife (ref string a) {.

  5. "IDE0059: Value assigned to variable is never used" is ...

    If it is, the diagnostic is correct, and it working as intended. The assignment in bool check = true; is unnecessary since it's always reassigned to false - the diagnostic wants you to write bool check;, and the associated quick fix makes this change. What's confusing is the message, and this was changed in #35494.

  6. Incorrect IDE0059: Unnecessary assignment of a value (simple ...

    The same thing happens if I move the assignment (here we do have a double assignment, but it is not unnecessary in case of errors, even if they all get caught, it does make a difference for the following code):

  7. Code-style language and unnecessary code rules

    Code-style language rules affect how various constructs of .NET programming languages, for example, modifiers, and parentheses, are used. This category also includes rules that identify parts of the code base that are unnecessary and can be refactored or removed. The presence of unnecessary code indicates one of more of the following problems ...

  8. Incorrect analysis: IDE0059 Unnecessary assignment of a value

    Yep, it's a bug. VS 2019 16.3.3. When I assign a value to an int that's outside of a do-while loop, where I want the int to have an initial value before the loop, and then change the value inside the loop, in this case, it says it's not needed and I should use a discard. This is wrong. If I let you do that, my variable won't get the initial value.

  9. VS underlining variable saying unnecessary assignment of a value

    VS underlining variable saying unnecessary assignment of a value. So the line is. string response = string.empty; And VS is just giving me a warning saying what I mentioned in the title. Explicitly assigning stuff like that is just a habit I have now due to a hold over from my VB days when you'd think something was a decimal but it was an int ...

  10. IDE0058: Remove unnecessary expression value

    This improves performance by avoiding unnecessary computation. If the expression has side effects, replace the left side of the assignment with a discard (C# only) or a local variable that's never used. This improves code clarity by explicitly showing the intent to discard an unused value. _ = Compute(); Options

  11. IDE0059: Unnecessary assignment of a value to variable

    Depending on whether a given radio button is checked, the variable can either have a value of "AM" or "PM." But in the statements where I assign the value, Visual Studio says that the assignment is unnecessary. I've stepped through the code and it's not stopping my code from running or anything, but I'm curious as to why it's happening.

  12. c#

    1. I have question about unnecessary assignments of variables. I have lot of functions and some of them when they catch exception they will write it into logfile. For example this is one of them (Just rename PC using powershell): try. Runspace rs; rs = RunspaceFactory.CreateRunspace(); rs.Open();

  13. Unnecessary assignment of a value to 'output' fix? : r/learncsharp

    Remove unnecessary value assignment (IDE0059) int v = Compute(); // IDE0059: value written to 'v' is never read, so assignment to 'v' is unnecessary. My code is this:- (obviously simplified) Random random = new(); return random.Next(0, number); You set v to a value, but you then overwrite the value before anything reads it, so there's no point ...

  14. CS0219 or new warning for unused variable when language ...

    The second setting (csharp_style_unused_value_assignment_preference) tells the IDE how to behave when you try to assign something to an otherwise unused variable, which, now that you've clarified your intent more, sounds like what you want. So if you had csharp_style_unused_value_assignment_preference = discard_variable:warning:

  15. Discards

    Discards are placeholder variables that are intentionally unused in application code. Discards are equivalent to unassigned variables; they don't have a value. A discard communicates intent to the compiler and others that read your code: You intended to ignore the result of an expression. You may want to ignore the result of an expression, one ...

  16. c#

    Here is my code. public void players_ready() add_cents_player(player_1, add_cents); player = player + cent_v; I want to be able to call this function and input whoever is the active player (player) and increase their value by (cent_v). However, player = player + cent_v; is saying "Unnecessary assignment of a value to 'player" and I don't ...

  17. Unnecessary assignment of value to 'definedVariable'

    _ usually denotes a throwaway value that you don't need and don't use anywhere else. For example if you don't print x, then why do you assign it? I am not sure if your warning is related to something like this; anyway you can probably turn off these kind of warnings somehow if it bothers you :)

  18. The JIT compiler is using unnecessary assignment of a value

    C#: Unnecessary assignment of a value to 'l' JIT: Hold my Beer! Explanation: 1.In method C the compiler needs to emit a bounds check and it does so by reading it from memory where the Lenght field is stored.. 2. In method D the compiler caches the field in a register since it was assigned to a local, although it's not used explicitly.. Not sure if this is a bug but it's Damn Awesome :)

  19. net core error unnecessary assignment of a value

    c# An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming. 10,534 questions

  20. IDE0059 Unnecessary assignment of a value...-VBForums

    C#; IDE0059 Unnecessary assignment of a value... If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below. Results 1 to 3 of 3 ...

  21. IDE0059 Unnecessary assignment of a value to 'result'

    2. Both branches of the if and the else assign a value to result, so you don't need to initialize it with null. This null is never read and will just be overwritten anyway. ... and unnecesary assignments can hide errors when you for instance later change that if/else.