3

I have a method Test which accepts x as an optional parameter. X can accept positive,negative and zero value. I need to check if double is null then print the value of x else if double value is null then print its null. As default value of double is 0 and double can't be assigned to null, so how can i do this?

public static void Test([Optional] double x)
{
           //if x is not null print value of x

            //else print x is null
}
static void main()
{
    Test();-output expected x is null
    Test(5);-output expected x is 5
    Test(0);--output expected x is 0
    Test(-1);-output expected x is -1
}
  • 10
    `double` can never be null because it is a value type. If you want to allow null, you will need to use `Nullable` (`double?`). – Johnathan Barclay Mar 04 '20 at 09:38
  • did you mean zero (which is `double`s-default-value) instead of `null`? – MakePeaceGreatAgain Mar 04 '20 at 09:38
  • `double` cannot be null, but you can replace it with `double?` which is a `Nullable` type of `double`, which means it accepts everything that double can accept and `Null` – styx Mar 04 '20 at 09:39
  • I was asking about double value.Please read full content of my post to get the requirements –  Mar 04 '20 at 09:40
  • 3
    @AsitSahoo `double` *CANNOT* be null, so therefore there's no need to check for it – styx Mar 04 '20 at 09:41
  • public static void Test([Optional] double x) { //if x is not null print value of x //else print x is null } static void main() { Test(); Test(5); Test(0); Test(-1); } How to do? –  Mar 04 '20 at 09:42

3 Answers3

9

[Optional] does not mean that if your arg is not present, it´s automaticylly null. Instead its an indicator that in case of an argument not being provided, it should get its default-value, which for double is not null, but 0.A double cannot be null, unless you mean Nullable<double> or double? (which are synonyms). So in your case these two calls are completely identical:

Test();
Test(0);

If you want to distinguish between an arg being passed and being zero, you should use a Nullable<double> instead:

public static void Test([Optional] double? x)
{
    if(x == null)
    {
        Console.WriteLine("null");
    }
    else
    {
        Console.WriteLine("" + x);
    }
}

Now you can call it like Test which will evaluate to Test(null).

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • 1
    Please don't use `x == null` on anything. Instead, use `x is null`. Admittedly, in this case it doesn't matter, but you might run into problems with `== null` in other cases - so it's best to get used to use the best practice any time. For not null, use `x is object`. For more information, read [The perfect non-null test](https://zoharpeled.wordpress.com/2019/11/13/the-perfect-non-null-test/) over on my blog. – Zohar Peled Mar 04 '20 at 10:17
0
public static void Test([Optional] double? x)
{

           if(x == null)
           {
                Console.WriteLine("null");
           }
           else
           {
                Console.WriteLine("" + x);
           }

}

Once upon a time, there was a person that was confused about the definition of types, and had, unbeknownst to him, chosen the wrong type to handle an input parameter. You see, he was expecting to pass a non existing value, called null into a method, however, the chosen datatype, did not allow for the value "null" to exist. In order to accomplish this task, a wise and helpful developer, simply showed him the error of his datatype choice, by writing a little more explicit pseudo code, that showed him the error of his ways. By coincidence, the pseudo code passed a compiler check. Funny how life works out.

Morten Bork
  • 1,413
  • 11
  • 23
  • 2
    Code only answers aren't really helpful for such questions. Explanations should be added – Cid Mar 04 '20 at 09:47
  • Please don't use `x == null` on anything. Instead, use `x is null`. Admittedly, in this case it doesn't matter, but you might run into problems with `== null` in other cases - so it's best to get used to use the best practice any time. For not null, use `x is object`. For more information, read [The perfect non-null test](https://zoharpeled.wordpress.com/2019/11/13/the-perfect-non-null-test/) over on my blog. – Zohar Peled Mar 04 '20 at 10:15
  • @ZoharPeled The results will be the same, unless you overload the equality operator. Just because C# 7.0 included the is null check, doesn't mean it is automatically best practice? what if you don't want a type check in your null comparison? – Morten Bork Mar 04 '20 at 11:26
  • @MortenBork using `is null` does not perform a type check. It only checks for `null`. You are correct about one thing - the results will be the same in most cases, unless someone overloaded the equality and inequality operator (and perhaps some other strange edge cases) - but that's exactly the point - the `is` operator can't be overloaded so you **know** it will **always** give you a correct result - therefor it's a better option since you don't need to know the type of the variable you're actually testing. – Zohar Peled Mar 04 '20 at 11:30
  • @ZoharPeled Well, what if you want to overload the equality operator? Then "is" would have to be replaced through your code, as you can't overload it. – Morten Bork Mar 04 '20 at 11:35
  • @MortenBork My point is that it's **safe** to use the *is* operator in `null` tests, regardless of the `==` (and `!=`) operator. They may be overloaded and mey not be overloaded, but that shouldn't matter in case of `null` tests. and while I can't imagine anyone would want to overload them to give incorrect results - I have [seen that happen](https://stackoverflow.com/a/55237082/3094533) from time to time. Call me paranoid but I would rather trust the framework than some unknown dev, be it from my company or from some 3rd party component. – Zohar Peled Mar 04 '20 at 11:39
  • @ZoharPeled lets say they wanted it to overload it, not to change it, but to implement an observer pattern on null checks? Simply because you can't imagine it, doesn't mean it can't be done. – Morten Bork Mar 04 '20 at 11:42
  • @MortenBork I said I can't imagine is wanting it to return the wrong results. That being said, "best practice" doesn't mean "any other way is wrong" - it means that in standard situations, that's the best course of action. What you're describing now is hardly a standard situation - and I'd even dare to say that if a null check changes the state of your instance, than your design is strange to say the least, if not flat out wrong. (That's not to say it *can't be* a good design for some edge cases, though I can't think of any such use cases of the top of my head). – Zohar Peled Mar 04 '20 at 11:50
  • @ZoharPeled Who said anything about altering the result? You could simply add an observer, that notifies a monitor whenever a null check is positive. (Creating a log of whenever a value is actively set to null) - for example. Consider that it normally doesn't happen that you override it, then why create a syntax, that doesn't allow it? The edge case could be a valid case, we aren't sure. But we then build an operator that actively prevents it? Then we can't do it. How is that in anyway best practice? That is is just ... inadvertent obfuscation of functionality. – Morten Bork Mar 04 '20 at 13:44
  • @MortenBork In that case, I would claim that adding such a functionality built into the `==` or `!=` operator is an obfuscation, and a violation of the Single Responsibility Principle. An operator should do it's own operation, nothing less, nothing more. It's easy enough to add such functionality in it's own method - `bool LogIfNull(T test) where T : class { var isNull = test is null; if(isNull) {/* log here */}}`. By using that in an operator on type `T` you're also creating a dependency between `T` and whatever logger you're using, that might not have to be there otherwise. – Zohar Peled Mar 04 '20 at 13:53
  • @ZoharPeled So removing the option to do an extension on an operator is considered best practice for a language, that is built on being able to extend existing functionality? Because that is what you are claiming here. – Morten Bork Mar 05 '20 at 07:47
  • @ZoharPeled I am not asking for anyone's credentials. You stated, that "it is best practice" to always use is null. I object to that statement alone. Not your blog, Or Jared Parsons. But stating something is best-practice, then it actually has to be best practice. And that is disagree with. And the implication that you wouldn't be able to extend an operator reliable, is laughable. Follow you SOLID principles, and you will have verified it to work, and it will be reliable. I trying to apply nuance to statement that is far to absolute for it's own good. – Morten Bork Mar 05 '20 at 09:24
  • Well, I guess we will have to disagree on that. – Zohar Peled Mar 05 '20 at 09:37
0

nullable double => double? use double questionmark => ??

double? d1;
d1 = null;
double? d2;
d2 = 123.456;
double safe1 = d1 ?? 0.0;
double safe2 = d2 ?? 0.0;

Console.WriteLine($"d1={d1}, d2={d2}");
Console.WriteLine($"safe1={safe1}, safe2={safe2}");