I'm getting an error message that I can't seem to figure out. I see that there are many other similar questions posted but the solutions don't seem to be working for me.
Error Message:
'PaymentPlanStoreLogic.Class1.myLog' is a 'field' but is used like a 'type'
My Code:
using System;
using PaymentPlanLogic;
namespace PaymentPlanStoreLogic
{
public class Class1
{
Logger myLog = new Logger();
myLog.createLog();
}
}
Object Browser:
public void createLog()
Member of PaymentPlanLogic.Logger
I have tried the following as suggested on the page (object) is a 'field' but is used like a 'type'
PaymentPlanLogic.Logger.createLog();
But I get the error
"'PaymentPlanLogic.Logger.createLog()' is a 'method' but is used like a 'type'"
You can't call a method on a field outside of a method:
using System;
using PaymentPlanLogic;
namespace PaymentPlanStoreLogic
{
public class Class1
{
Logger myLog = new Logger();
void YouForgotThisMethod()
{
myLog.createLog();
}
}
}
Tobsey's answer is correct. The reason for the odd error message is because the compiler is trying desperately to figure out what you mean. The reasoning goes like this:
The only things that are legal at this point are declarations of classes, interfaces, structs, enums, fields, operators, indexers, events, properties, methods, constructors and destructors. It can't be a class, interface, struct or enum because those all have a keyword in them. It can't be a constructor or destructor. Therefore the user must be attempting to make a field, operator, indexer, event, property or method. All of those things may legally begin with a type. OK, so this expression must be attempting to identify a type. But it doesn't identify a type; it identifies a field. So that's the error I'll give.
Of course that is an unjustified anthropomorphization of the compiler, but you take the point: the compiler's "mental model" of erroneous code is very different from what you were thinking when you wrote the broken code, and so the error message is not very helpful. The compiler thinks that you know that a statement can't go there, and have mixed up a field with a type. A more sophisticated algorithm would have the compiler guess that since what you typed is a legal statement, that the real error is that the statement is outside of a block.
Writing error message generators that accurately model the mental processes of people who are writing broken code is quite difficult.
The definition of Class1
is incomplete. You cannot call this method within the class, you can call it within a method of the class:
using System;
using PaymentPlanLogic;
namespace PaymentPlanStoreLogic
{
public class Class1
{
#region Members
Logger myLog;
#endregion
#region Constructors
public Class1()
{
myLog = new Logger();
myLog.createLog();
}
#endregion
}
}
Then createLog()
would execute upon instantiating a new instance of Class1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With