How to Resolve Error "CS0670: Field cannot have void type" in C#
The Compiler Error CS0670 is a type definition error. The message reads: "Field cannot have void type".
In C#, void is a special keyword used exclusively to specify the return type of a method that does not return a value. It is not a data type that can hold a value. Since a Field (a class-level variable) exists specifically to store data, declaring a field as void is logically impossible because "nothing" cannot be stored.
This guide explains why this error happens and how to fix your field definitions.
Understanding the Void Keyword
- Valid Use:
public void MyMethod() { }(This method performs an action and returns nothing). - Invalid Use:
public void MyVariable;(Create a storage box that holds nothing).
Since a field is a storage location in memory (e.g., 4 bytes for an int, 8 bytes for a long), the compiler must know what kind of data to put there. void has no size and no representation in memory storage.
Scenario: The Invalid Declaration
This error often occurs due to copy-paste mistakes (copying a method signature but forgetting the parentheses) or a misunderstanding of how to represent "empty" data.
Example of error: copying a method definition but trying to make it a field.
public class DataHandler
{
public int Id;
// ⛔️ Error CS0670: Field cannot have void type.
// The developer might have meant to write a method 'ProcessData',
// or meant to use a different type.
public void ProcessData;
}
Solution: Use a Valid Data Type
If you intended to store data, change void to a real type. If you intended to define an action, convert the field into a method or a delegate.
Fix 1: Change to a Type (Variable)
If you just want a generic placeholder, use object.
public class DataHandler
{
// ✅ Correct: Using a valid type
public object ProcessData;
}
Fix 2: Convert to Method (Action)
If you meant to define a function, add parentheses.
public class DataHandler
{
// ✅ Correct: Added '()' to make it a method
public void ProcessData()
{
// Code here
}
}
Fix 3: Use a Delegate (Function Pointer)
If you want a field that holds a reference to a void method (so you can assign different functions to it), use the Action delegate.
using System;
public class DataHandler
{
// ✅ Correct: 'Action' is a type that points to a 'void' method.
public Action ProcessData;
}
// Usage:
// handler.ProcessData = () => Console.WriteLine("Processing");
Conclusion
CS0670 prevents you from creating variables that cannot hold values.
- Check the Syntax: Did you forget the
()on a method declaration? - Check the Intent: Do you want to store a function? Use
ActionorDelegate, notvoid. - Check the Type: Do you want to store data? Use
int,string,bool, etc.