creating a class in C#, use of unassigned variable
I recieve a "use of unassigned varable in InfoPeople". I am not sure why, my class is set up as the example in the textbook. Could someone shed a little light on this. Thanks.
class personInfo
{
public string fName;
public string lName;
public int personID;
}
class Program
{
static void Main(string[] args)
{
personInfo InfoPeople;
InfoP开发者_Go百科eople.fName = "jeff";
Console.WriteLine("the fName is: " + " " + InfoPeople.fName);
}
}
You haven't initialised your instance:
personInfo InfoPeople = new personInfo();
I would try and conform to C# style type/casing conventions:
PersonInfo infoPeople = new PersonInfo();
You need to new
your object instance like this:
personInfo InfoPeople = new personInfo();
That's just the C# syntax for creating new object instances.
It doesn't work because InfoPeople
is a variable that holds a reference to a personInfo
, but you never actually created a personInfo
.
Fix it by saying:
personInfo InfoPeople = new personInfo();
By the way, your naming convention isn't very conventional. People generally PascalCase class names and camelCase variables. Try to follow that convention so that your code is easier to understand.
In C#, you must assign a value to a local variable before it is used -- local variables do not default to anything (not even the default value of the type!).
As others have pointed out, the correct solution is likely to use a new personInfo()
. However, just assigning null
to the InfoPeople
variable (above where it is used) will get rid of the compile-time error (and get a NullReferenceException
at run-time ;-)
(That is, the compiler error has nothing to do with InfoPeople
containing an "invalid" value -- it only cares that some value has been previously assigned.)
Happy coding.
Extra tip:
// C# allows one to instantiate a new object
// and assign members at the same time.
personInfo InfoPeople = new personInfo {
fName = "jeff",
};
change you first line in main() function as below. You specified the object type with "personInfo InfoPeople
" statement but did not allocate memory. When you do that with 'new()' keyword, it actually creates object in memory, and that is what the error for.
personInfo InfoPeople = new personInfo()
You declare the local variable of type personInfo
named InfoPeople
, but you don't assign a value to it before trying to use it. The compiler can prove this and therefore it complains. Simple enough.
Have to instantiate an instance of personInfo
class personInfo
{
public string fName;
public string lName;
public int personID;
}
class Program
{
static void Main(string[] args)
{
personInfo InfoPeople = new personInfo();
InfoPeople.fName = "jeff";
Console.WriteLine("the fName is: " + " " + InfoPeople.fName);
}
}
You didn't set InfoPeople to a new instance of personInfo:
personInfo InfoPeople = new personInfo();
Don't you need to instantiate that as new?
"New personInfo" you have to instantiate the object from the class
精彩评论