Reputation: 3642
I know with the new C# 6.0 you can check for null in the following simplified example:
MyClass myClass = new MyClass();
string example = myClass?.someFieldInMyClass;
This is a more concise way to check for nulls. Great!
I'm curious if there is a way to check if a local variable or parameter being passed in is null using the new operator. So if a parameter was passed to a method like so:
public static void SomeMethod(mytype t)
{
AnotherClass.myfield = t;
}
Is there a way to check if t
is null? I've been looking around the documentation and haven't found anything.
I'm looking for something like Anotherclass.somefield = ?t;
Is the expectation that you would check it before passing it? The reason I want to do this is I am passing in a custom type, which is a property on another class. I am then setting the other class with the custom property I'm passing in.
Maybe this is just code smell, I'm open for suggestions.
Upvotes: 1
Views: 426
Reputation: 2254
I'm not sure what you are trying to accomplish but if you want to avoid overwriting the value of
AnotherClass.myfield
With a possible null t then you can just do this
AnotherClass.myfield = t ?? AnotherClass.myfield;
Then it will only change the assignment of myfield if t is NOT null, otherwise it will keep its previous assignment (reassign).
Upvotes: 3