VB -> C#: Field initializers referencing non-static fields
See original GitHub issueInput code
Public Class A
Private x As Integer = 2
Private y(x) As Integer
End Class
Erroneous output
public class A
{
private int x = 2;
private int[] y = new int[x + 1];
}
Expected output
public class A
{
private int x = 2;
private int[] y;
public A()
{
y = new int[x + 1];
}
}
Details
Product in use: VS extension
Version in use: 6.6.0
Accessing a non-static field in C# is an error, where it allowed in VB (CS0236).
It’s a bit more complicated than this, since you need to account for multiple constructors.
Issue Analytics
- State:
- Created 4 years ago
- Comments:10 (5 by maintainers)
Top Results From Across the Web
c# - Conceptual reason of the 'A field initializer cannot ...
I'm not sure about a field, but it seems rational to deny field initializers access to properties or methods. For example:
Read more >Compiler Error CS0236
A field initializer cannot reference the non-static field, method, or property 'name'. Instance fields cannot be used to initialize other ...
Read more >[Solved] A field initializer cannot reference the non-static ...
A variable initializer for an instance field cannot reference the instance being created. It means you can't initialize one instance member* ...
Read more >Re: A field initializer cannot reference the non-static ...
Re: A field initializer cannot reference the non-static field, method, or property. textBox1 and textBox2 are fields, i.e. member variables, and ...
Read more >C# 6.0 - A field initializer cannot reference the non-static field ...
The reason for the error is that the method GetCurrentDate is NOT marked as static . Setting the method static as shown below...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@GrahamTheCoder " I don’t know what the VB order is"
The VB Initializers run within the constructor before any other constructor code in the sequence top to bottom as they are defined in the class.
So the VB code:
translate to c# as:
I’m consolidating the remainder of #418 here: The reference to a non-static might be inside a lambda, but the initialization it still needs to be moved to the constructor: