Compiler Error CS0165

Joshua Grossman 126 Reputation points
2022-01-23T14:34:56.47+00:00

My code is something like this
Rectangle area;
ref Rectangle local = ref area;
and I get this error "Severity Code Description Project File Line Suppression State
Error CS0165 Use of unassigned local variable 'area' SuperTabs C:\Users\JSGro\source\repos\SuperTabs\SuperTabs\BaseTabRenderer.cs 497 Active
"
Someone please help

Thanks,
Joshua Grossman

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2022-01-23T14:56:43.65+00:00

    If you change this:

    Rectangle area;
    

    To:

    Rectangle area = new Rectangle();
    

    The error is telling you that you're attempting to use a local variable that it can statically determine won't have a value when you come to use it. If Rectangle was a reference type i.e. a reference to an object that was allocated on the heap then this inference would be true. However in your case Rectangle is a value type, where it's possible for the compiler to infer a default value. There is a caveat to that in your case though.

    Normally local variables where the type is a value type (such as int, bool, short, etc..) you don't need new to explicitly instantiate them before you can start using them. They will be given a default value of default(T) (e.g. 0 for int, false for bool, or for reference types it'll be null), but structs (which are also value types) are a special case because they have properties hanging off them, so they may need to have new X() assigned to them before you can use them if the struct has any properties that also need to be initialised.

    For example, Rectangle has Top, Bottom, Left and Right properties among others. The C# language designers may have thought allowing value types to have their values defaulted was reasonable, but defaulting the values of properties hanging off those value types wasn't explicit enough.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.