Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get close to non-nullable reference types in C# today?

Tags:

I've read many of the non-nullable questions and answers. It looks like the best way to get close to non-nullable types in C# (4.0) is Jon Skeet's NonNullable<> hack.

However, it seems that C++/CLI has solved much of the problem by supporting managed references: Foo% (instead of native C++ Foo&). The compiler makes this work by adding modreq(IsImplicitlyDereferenced) to the argument. Trying to call such a function from C# results in:

'<FunctionName>' is not supported by the language 

Is there anything better then NonNullable<>?

Is there any way to (reasonably--i.e., w/o using reflection) call a C++/CLI method Foo::Method(Bar%) from C#?


[edit] It seems there is currently nothing better than NonNullable<>...I wish I would have gotten some comments on the C++/CLI stuff as it already has at least a partial solution.

like image 475
Ðаn Avatar asked Feb 02 '10 04:02

Ðаn


People also ask

What is a non-nullable reference type?

A reference isn't supposed to be null.The default state of a nonnullable reference variable is not-null. The compiler enforces rules that ensure it's safe to dereference these variables without first checking that it isn't null: The variable must be initialized to a non-null value.

What is #nullable disable?

Nullable disable as the default: disable is the default if you don't add a Nullable element to your project file. Use this default when you're not actively adding new files to the codebase. The main activity is to update the library to use nullable reference types.

Should I use nullable reference types?

Although using nullable reference types can introduce its own set of problems, I still think it's beneficial because it helps you find potential bugs and allows you to better express your intent in the code. For new projects, I would recommend you enable the feature and do your best to write code without warnings.


1 Answers

I've run into this a few times...I've yet to find anything better than Skeet's solution. It's solved all the cases I've come across, so I have to give it my vote.

I agree it's a bit of a hacky situation that we have to resort to that...but his fix does solve the problem.

like image 135
Nick Craver Avatar answered Sep 29 '22 21:09

Nick Craver