Is there a way to do some kind of zero coalescing on a property in C #?

I am not quite sure how to formulate this question, but the scenario is as follows:

Let's say I have the following class:

public class SampleClass
{
    public int Number { get; set; }
}

I know that you can ignore the associated class:

SampleClass newSampleClass = possibleNullSampleClass ?? notNullSampleClass;

Is it possible to somehow execute some null coalesce property on the property, so I don't need to do this:

int? num = sampleClass != null ? new int?(sampleClass.Number) : 5;

It seems like it would be very helpful to have something like an operator ???to perform this check so that I can:

int? num = sampleClass.Number ??? 5;

Is something like this possible in C #?

+3
source share
5 answers

There is currently no such operator. But in C # 6, "safe navigation" will appear, and you can write

int number = sampleClass?.Number;

NullRef, sampleClass null. , -:

public static TResult Maybe<TSource, TResult>(
    this TSource source, Func<TSource, TResult> produceResult, Func<TResult> produceDefault)
    where TSource : class
{
    return source == null ? produceDefault() : produceResult(source);
}

:

int numberOrFive = sampleClass.Maybe(c => c.Number, () => 5);
+5

. .

, , , :

public static TResult Access<TSource, TResult>(
    TSource obj, Func<TSource, TResult> selector, TResult defaultIfNull)
    where TSource : class
{
    if (obj == null)
        return defaultIfNull;
    else
        return selector(obj);
}

SampleClass sampleClass = null;
int num = Access(sampleClass, s => s.Number, 5);

( , , . , Use.)

+3

Servy. , , , .

public static TResult Access<TSource, TResult>(
   TSource obj, Func<TSource, TResult> selector, TResult defaultIfNull)
   where TSource : class
{
    TResult result;
    try
    {
        result = selector(obj);
    }
    catch ( NullReferenceException)
    {
        result = defaultIfNull;
    }

    return result;

}

Thus, if you are trying to access ZipCode = Customer.Address.ZipCode;

Are you protected if any client or address is null

0
source

You cannot do this in C #. You need to explicitly check for invalidation:

MyWidget x ;

int? v = x == null ?  (int?)x.SomeProperty : (int?) null ;

If you really think this would be useful, you can write your proposal to Microsoft Connect:

http://connect.microsoft.com/VisualStudio

I am ready to be what they thought about it, and decided that it’s not enough to delve into the language.

0
source

You can completely do this:

var x = (myObject ?? DefaultObject).Field;

And this...

var x = (myObject == null) ? myObject.Field : defaultValue;
0
source

All Articles