c# - What if you could create not-nullable reference type? -
have ever faced need of informing uses code , passes reference typed parameters not pass null? have. , should have thrown exceptions each "bad" variable code cannot work with.
now, let's imagine have created struct:
public struct notnullable<t> t : class { // backing field value. guaranteed return not null. private t _value; public t value { { if (_value == null) throw new applicationexception("value not initialized."); return _value; } } // easy both-ways convertible. public static implicit operator t(notnullable<t> notnullable) { return notnullable.value; } public static implicit operator notnullable<t>(t value) { return new notnullable<t>(value); } // these members overridden. public override string tostring() { return value.tostring(); } public override int gethashcode() { return value.gethashcode(); } public override bool equals(object obj) { if (obj notnullable<t>) { return value.equals(((notnullable<t>)obj).value); } return value.equals(obj); } public notnullable(t value) { this._value = value; } } usage of such structure:
class program { static void main(string[] args) { notnullable<string> = "hello world!"; console.writeline(a); console.writeline((string)a); console.writeline((object)a); console.writeline((notnullable<string>)a); // produces fine outputs. var b = default(notnullable<string>); console.writeline(b); // throws exception of non-initialized field. } } you make methods receive non-nullable reference typed parameters:
list<tree> treelist; public void createtree(notnullable<tree> tree) { // assume cannot have list contain nulls. treelist.add(tree); // no null-checks required. } what possibly wrong in such useful opposite nullable<> struct?
i fail see how advantageous throwing argumentnullexception. matter of fact, i'd rather this:
public void foo(myclass item, myclass2 item2) { if (item == null) throw new argumentnullexception("item"); if (item2 == null) throw new argumentnullexception("item2"); } this way let programmer know parameter bad. notnullable<t> imagine this:
public void foo(notnullable<myclass> item, notnullable<myclass> item2) { ... } foo((notnullable<myclass>)myvar1, (notnullable<myclass2>)myvar2); now "value not initialized." thrown in face. one?
Comments
Post a Comment