C
C#2mo ago
JTN

✅ null thingy (SOLVED)

quick question about nul
No description
12 Replies
JTN
JTN2mo ago
do i have to do Trainer1? everywhere or is there a shortcut? because everytime i want to use Trainer1 it needs a ? i geuss and the last line gives a warning that i dont know how to fix i am new to C# btw
Keswiik
Keswiik2mo ago
? tells the compiler that field can be null, which in turn lets your IDE know it should be telling you to add null checks to your code. First thing that I notice though is that all of your fields for Arena are static which isn't good.
JTN
JTN2mo ago
that is the task for school all the vars in arena must be static
IsNotNull
IsNotNull2mo ago
They probably are requiring static vars because they are easier to reason about when beginning, but it makes your code look unusual to experienced devs I think.
Keswiik
Keswiik2mo ago
^ huge reg flag for me, but makes more sense in a beginner school assignment you don't have to use ? when accessing your trainer fields, but it is a way to access properties and not cause exceptions if something is null.
IsNotNull
IsNotNull2mo ago
In most systems, the code is made up primarily of classes and there are patterns to ensure private fields are initialized when the class is constructed. Its an easier way to deal with the null syntax.
Keswiik
Keswiik2mo ago
for example
IsNotNull
IsNotNull2mo ago
If you are learning and finding the null reference handling annoying or confusing... you can also disable it. Its useful in larger projects, but I find it annoying sometimes when prototyping or for quick one-off projects.
JTN
JTN2mo ago
the reason i placed a ? is so the warning there went away
Keswiik
Keswiik2mo ago
Trainer t1 = null;
t1.SomeMethod() // this causes an exception
Trainer t1 = null;
t1.SomeMethod() // this causes an exception
Trainer t1 = null;
var someValue = t1?.SomeMethod() // this does NOT cause an exception, BUT if it would have returned a value, say a string, someValue would now be null
Trainer t1 = null;
var someValue = t1?.SomeMethod() // this does NOT cause an exception, BUT if it would have returned a value, say a string, someValue would now be null
Keswiik
Keswiik2mo ago
Member access and null-conditional operators and expressions: - C#
C# operators that you use to access type members or null-conditionally access type members. These operators include the dot operator - ., indexers - [, ], ^ and .., and invocation - (, ).
JTN
JTN2mo ago
i will Thanks