C# Compiler Error
CS0170 – Use of possibly unassigned field ‘field’
Reason for the Error
You will receive this error when C# compiler detected a field with-in a structure that was used without being initialized.
For example, the below code snippet will result with the error because the struct logData.Level was not initialized.
using System; namespace ConsoleApp2 { public struct Log { public int Level ; } class Program { public static void Main() { Log logData; Console.WriteLine(logData.Level); } } }
Error CS0170 Use of possibly unassigned field ‘Level’ ConsoleApp2 C:UsersSenthilsourcereposConsoleApp1ConsoleApp2Program.cs 14 Active
Solution
Ensure that you identify and initialize the struct variable that was uninitialized before its usage. The above code can be fixed as follows.
using System; namespace ConsoleApp2 { public struct Log { public int Level ; } class Program { public static void Main() { Log logData; logData.Level = 1; Console.WriteLine(logData.Level); } } }
Permalink
Cannot retrieve contributors at this time
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Compiler Error CS0170 |
Compiler Error CS0170 |
07/20/2015 |
CS0170 |
CS0170 |
ba881e38-2abf-4a5f-b9e6-28d26a5bd235 |
Compiler Error CS0170
Use of possibly unassigned field ‘field’
A field in a structure was used without first being initialized. To solve this problem, first determine which field was uninitialized and then initialize it before you try to access it. For more information about initializing structs, see Structure types.
The following sample generates CS0170:
// CS0170.cs public struct error { public int i; } public class MyClass { public static void Main() { error e; // uncomment the next line to resolve this error // e.i = 0; System.Console.WriteLine( e.i ); // CS0170 because //e.i was never assigned } }
I might be missing something, but I’m getting what I think seems an odd error, that none of the other developers are getting with the same code…
public void SomeMethod(... symbolInfo)
{
ElementId elementId = symbolInfo.GetElementIds().Head(true);
if (elementId.HasValue())
{
// error here "Use of possibly unassigned field 'Type'"
object element = repository.FindElement(elementId.Type, elementId.Id);
if (element != null) { ... }
}
}
public struct ElementId
{
public string Id;
public MDAPI_ElementType Type;
}
With the following extension methods:
public static bool IsEmpty(this ElementId id)
{
return id.Type == ElementType.ElementUnknown || string.IsNullOrEmpty(id.Id);
}
public static bool HasValue(this ElementId id)
{
return !id.IsEmpty();
}
Can anyone tell my why this won’t build?
Graham Clark
12.8k8 gold badges50 silver badges81 bronze badges
asked Nov 22, 2011 at 11:10
2
I’ve managed to fix my build error, by instead calling an extension method which directly takes the ElementId. I have no idea why this fixes the issue though!
public static object FindElement(this IMRepository rep, ElementId element)
{
return rep.FindElement(element.Type, element.Id);
}
answered Nov 22, 2011 at 11:32
IanIan
33.2k25 gold badges119 silver badges192 bronze badges
1
-
#1
Hey Guys,
Here is the code I am trying to compile:
using System;
class Exercise {
static void Main()
{
Point p;
p.x = 40.0;
p.y = 45.0;
if (NormalizePoint(out p)) {
Console.WriteLine ($"x normalized to {p.x}ny normalized to {p.y}");
} else {
Console.WriteLine ($"Points cannot be normalized");
}
}
public struct Point
{
public double x;
public double y;
public Point (double _x, double _y)
{
x = _x;
y = _y;
}
}
public static bool NormalizePoint (out Point p)
{
if (p.x < 1d || p.y < 1d) return false;
if (p.x > 100d || p.y > 100d) return false;
p = new Point (p.x / 100d, p.y / 100d);
return true;
}
}
When attempting to compile using mcs (Mono C# compiler version 6.8.0.123) I get the following errors:
struct.cs(32,10): error CS0170: Use of possibly unassigned field `x'
struct.cs(32,22): error CS0170: Use of possibly unassigned field `y'
struct.cs(30,48): error CS0177: The out parameter `p' must be assigned to before control leaves the current method
I’ve omitted some of the above errors as it repeats.
To eliminate the last compilation error there I extended the body of the if statements within NormalizePoint to assign p to itself as the struct’s values should not change.
This gets a warning from the compiler so I know I’m going about this the wrong way. What would be the better way to achieve what I’m trying to do here in regards to
using an out variable within a function which may not modify the variable under certain conditions?
For the first two methods, I understand what the compiler is telling me, I just don’t see how it applies to the code (maybe I don’t understand). I don’t really know what to do
to resolve this error as I am under the impression that the struct and it’s fields are initialized within Main before it is passed to NormalizePoint.
Any help and suggestions would be greatly appreciated.
Thank you
-
#2
The out keyword is for parameters used ONLY to pass data out of a method. I’m not 100% sure but I think that out parameters may even be implicitly set to the default value for their type. If you want to use a parameter to pass data in and out then you use ref rather than out.
-
#4
Thank you for the link @Sheepings ! I will give that a read over.
-
#5
It so nice to see a young dev using structs, as they are so undervalued and under used in functional programming. However… I don’t have time to dig into this :
if (p.x < 1d || p.y < 1d)
=> You can’t do that. Your struct has no default value. And Out is not correct in that context.
Adding p = default;
before the if statement is an improvement, but also not correct in the way of what you’re doing. Your struct has no default value.
Instead, notice how changing your method to : public static bool NormalizePoint (ref Point p)
removes the errors?
You have quite a bit of refactoring to do.
-
#6
@Sheepings reading through the article you posted lead me to the solution you provided in your second post there. Now I understand why the two compiler errors were directly related to how the struct was being passed into the method.
Thank you
-
#7
You’re are most welcome. If you need any other help, you know where we are. Always happy to help.
Guest
-
#1
qaHi,
I am trying to assign value to a member of object of a struct, the object is
treated under foreach.
I got the error : error CS0170: Use of possibly unassigned field ‘price’
according to a thread in same group it is bug with C# 7.0, 7.1
» It is
caused by having semi-large structs or just a large number of structs as
locals»
Is there any SP, Another version?
I’ve universal subscription of MSDN and got lots of DVDs. If you tell me the
number of the disc, it would save me some time.
Thanks,
Fahad Ashfaque
Advertisements
Nick Malik [Microsoft]
-
#2
Hello Fahad,
qaHi,
I am trying to assign value to a member of object of a struct, the object is
treated under foreach.I got the error : error CS0170: Use of possibly unassigned field ‘price’
according to a thread in same group it is bug with C# 7.0, 7.1
» It is
caused by having semi-large structs or just a large number of structs as
locals»
Interesting. I went looking for that thread and didn’t find it, in this
group or any other. I’d love to learn the circumstances around that one.
Of course, that may or may not be your problem. How about if you post some
code?
This error is most often caused by the use of a field within a struct
without you having assigned the struct first.
Is there any SP, Another version?
What version and sp are you using? .Net framework 1.1 is up to SP1, .Net
framework 1.0 is up to SP3
I’ve universal subscription of MSDN and got lots of DVDs. If you tell me the
number of the disc, it would save me some time.
Sorry. I don’t have the MSDN personally. You have an index on the first
disk. That will tell you what disk to find the framework service packs on.
—
— Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik
Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I’m just a
programmer helping programmers.
—
Mohamoss
-
#3
Hi Fahad
What I suggest is that you contact your local Microsoft support as they
would route you within MS as needed and if there is a hot fix for that
they will send it to you. Since you have an MSDN your are entitled to 2
free support incidents at least depending on type of your MSDN
subscription. .Mohamed M .Mahfouz
Developer Support Engineer
ITWorx on behalf of Microsoft EMEA GTSC
Bruce Wood
-
#4
Before you call MS, post the code that is giving you the error
(preferably an entire method) so that we can look at it. Perhaps it’s
something that we can explain, that will save you using up one of your
support calls.
Guest
Advertisements
Nick Malik [Microsoft]
-
#6
Hello Fahad,
The last message wasn’t posted my an MVP. It was posted by a Microsoft
employee.
I’ll ask around.
—
— Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik
Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I’m just a
programmer helping programmers.