Is this a false warning when using LINQ to SQL?

In the many LINQ examples I've seen, I create my own data and table context using code similar to the one below:

class MyDatabase : DataContext { public Table<Widget> Widgets; public Table<Car> Cars; public MyDatabase (string connection) : base(connection) { } } 

But for each table (Widgets, Cars, etc.) I get a warning. The table_name field is never assigned . I cannot find anyone on Google who also has this problem. I don’t feel like I am doing something wrong, because I am simply copying LINQ examples that I saw from different places. So what about this warning? Does this warn me of a real problem? Or am I missing something?

+3
source share
3 answers

Yes, they are false. *

In this other question about how a DataContext works , we learn that the constructor for a DataContext uses reflection to populate fields at runtime. Therefore, Visual Studio gives you a warning based on the knowledge that it has at compile time. He does not know that ultimately these fields are filled before they are consumed.

* The answer is based on another comment found on SO. Maybe I’m even mistaken!

+3
source

The warning is valid because you created a definition for widgets and cars, but they are not assigned. This should take care of itself when you create your data context. You will eventually turn to them.

0
source

You can solve this problem by setting them to null after the declaration.

The response comment - it should not be on the same line as the declaration - anywhere after the announcement and before its use. The same line is common and often used for initializers, as required, and why the compiler complains.

0
source

Source: https://habr.com/ru/post/1299987/


All Articles