Ternary operator in C# to look code cleaner

I am sorry for asking this stupid question.

I know that ternary operator has made developers' life very easy. I have a question in my mind.

Suppose I have to check whether something is DBNull.Value or not, if it is then assign '0' or keep the value as it is. I do this like below

string str = dt.Rows["Col"] == DBNull.Value ? "0" : dt.Rows["Col"].ToString():

It works fine but if my expression is big then it results ugly code like

int CL = (int)Math.Round((Convert.ToInt32(dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'") == DBNull.Value ? 0 : dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'")) * Total_Leaves) / 100d);

look at repetition of code in that. Can I make it look little simpler.

I know ?? is a cleaner way to check for null is there anything for DBNull.Value or "" ?

Thanks

-------------Problems Reply------------

I used extension method for that. Thanks to mike z for the comment :)

public static class Extensions
{
public static object DefaultIfDBNull(this object obj, object _default)
{
return obj == DBNull.Value ? _default : obj;
}
}

and calling code

int CL = (int)Math.Round((Convert.ToInt32(dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'").DefaultIfDBNull(0)) * Total_Leaves) / 100d);

though it is not a proper answer but it make it cleaner and usable :)

Can I make it look little simpler.

Yes, at the minute your method checks if compute is null and then returns 0 if it is so you can start by extracting the common method

var computed = dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'");
int CL = (int)Math.Round((Convert.ToInt32(computed == DBNull.Value ? 0 : computed) * Total_Leaves) / 100d)

But you can go further by putting this into a method and then just returning 0 if it is null

private int GetComputed(int Total_Leaves)
{
var computed = dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'");
if(computed == DBNull.Value)
return 0;
return (int)Math.Round(Convert.ToInt32(computed) * Total_Leaves) / 100d;
}

You could wrap the test in a simple method something like the following:

public static string GetString(Object testObject)
{
return testObject == DBNull.Value ? "0" : testObject.ToString();
}

Its basically the same but you don't have your ternary test all over the place.

Your code would be something like:

(int)Math.Round((Convert.ToInt32(GetString(dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'"))) * Total_Leaves) / 100d);

It requires you to convert the string result though - so not a perfect solution for all cases.

Category:c# Views:0 Time:2018-02-11

Related post

  • PHP Ternary Operator not working for this code 2011-04-11

    i would like to use Ternary Operator for the below code.. <?php if($users['active'] == 1 ) { echo 'Yes'; } else { echo 'No'; } ?> i tried using this code and it does not work.. <?php ($users['active'] == 1) ? echo "Yes" : echo "No"; ?> wh

  • Check Multiple Conditions In ternary operator in c# 2012-02-25

    I have three variables int a =10; int b=20; int c=30; int d=0; Now the thing i want to do that i want to use ternary operator and assign the greatest among (a,b,c) into "d" . Thanks in advance --------------Solutions------------- You can use Math.Max

  • Are there any languages in which the ternary operator can be used to modify code structure? 2011-04-13

    I am curious to know if there are any languages in which the ternary operator can be used to modify code structure at run time. Such as: boolean bool = true; // Addition method - can add 2 or 3 integers. add(5,10 bool ? ) : ,15); I would assume that

  • Which coding style you use for ternary operator? 2008-10-28

    I keep it in single line, if it's short. Lately I've been using this style for longer or nested ternary operator expressions. A contrived example: $value = ( $a == $b ) ? 'true value # 1' : ( $a == $c ) ? 'true value # 2' : 'false value'; Personally

  • Benefits of using the conditional ?: (ternary) operator 2010-07-22

    What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being: Conditional ?: Operator Shorter and more concise when dealing with direct value comparisons and assignments Doesn't seem to b

  • Ternary operator ?: vs if-else 2010-08-25

    In C++, is the ?: operator faster than if()...else statements? Are there any differences between them in compiled code? --------------Solutions------------- Depends on your compiler, but on any modern compiler there is generally no difference. It's s

  • Can the conditional operator lead to less efficient code? 2011-08-05

    Can ?: lead to less efficient code compared to if/else when returning an object? Foo if_else() { if (bla) return Foo(); else return something_convertible_to_Foo; } If bla is false, the returned Foo is directly constructed from something_convertible_t

  • Multiple conditions in the ternary operator safe? 2011-09-02

    I have seen advice that says the ternary operator must not be nested. I have tested the code below and it works okay. My question is, I haven't seen the ternary operator used like this before. So, is this as reliable as it were used in an if or could

  • How does the ternary operator work? 2009-01-20

    Please demonstrate how the ternary operator works with a regular if/else block. Example: Boolean isValueBig = value > 100 ? true : false; Exact Duplicate: How do I use the ternary operator? --------------Solutions------------- Boolean isValueBig =

  • Is this a reasonable use of the ternary operator? 2009-02-07

    Are there any understanding / maintainability issues that result from code like inVar1 == 0 ? NULL : v.push_back(inVar1); inVar2 == 0 ? NULL : v.push_back(inVar2); and so forth. The possibly confusing idea is using the ternary operator for program fl

  • Ternary operator: bad or best practice? 2009-03-29

    I'm looking for reasons to use/not to use it and for original ideas (in their use and to replace them). Duplicate: To Ternary Or Not To Ternary Related (but does not address the question being asked): Which coding style you use for ternary operator?

  • Looking for clean WinForms MVC tutorial for C# 2009-06-05

    How to create a rich user interface Windows application, example Photo Shop. I am looking for clean MVC tutorial for WinForms with C# somewhere. (Not ASP.NET MVC.) Being new on the Windows Platform; most MSDN and internet tutorials basically puts eve

  • Ternary operator associativity in C# - can I rely on it? 2009-11-19

    Ahh, don't you just love a good ternary abuse? :) Consider the following expression: true ? true : true ? false : false For those of you who are now utterly perplexed, I can tell you that this evaluates to true. In other words, it's equivalent to thi

  • How to use C#'s ternary operator with two byte values? 2009-12-11

    There doesn't seem to be a way to use C#'s ternary operator on two bytes like so: byte someByte = someBoolean ? 0 : 1; That code currently fails to compile with "Cannot convert source type 'int' to target type 'byte'", because the compiler treats the

  • Ruby ternary operator without else 2010-02-01

    Is there a ruby idiom for "If do-this," and "do-this" just as a simple command? for example, I'm currently doing object.method? a.action : nil to leave the else clause empty, but I feel like there's probably a more idiomatic way of doing this that do

  • unusual ternary operation 2010-04-17

    I was asked to perform this operation of ternary operator use: $test='one'; echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three'; Which prints two (checked using php). I am still not sure about the logic for this. Please, can anybody tell m

  • How to define a ternary operator in Scala which preserves leading tokens? 2010-04-24

    I'm writing a code generator which produces Scala output. I need to emulate a ternary operator in such a way that the tokens leading up to '?' remain intact. e.g. convert the expression c ? p : q to c something. The simple if(c) p else q fails my cri

  • c++ ternary operator 2010-07-15

    So I ran into something interesting that I didn't realize about the ternary operator (at least in Visual C++ 98-2010). As pointed out in http://msdn.microsoft.com/en-us/library/e4213hs1(VS.71).aspx if both the expression and conditional-expression ar

  • Is it possible to set multiple variables with one ternary operator? 2010-07-15

    I was looking to see if it's possible to set multiple variables with one ternary operator. I google'd a bit, but didn't come up with anything. I started testing a few ideas, and found something close -- but also getting some strange behavior; any ide

  • Can I make the ternary operator treat my class like a bool? 2010-08-20

    I've recently been doing a huge refactoring where I was changing a lot of my code to return booleans instead of an explicit return code. To aid this refactoring I decided to lean on the compiler where possible by getting it to tell me the places wher

  • Ternary operator in foreach 2010-09-01

    I am currently struggling with about 5 nested if-statements and its becoming quite confusing to look over all of them. So, I thought about adding ternary operators instead of ifs for simple checks, see foreach (String control in controls) { if (!cont

  • How to use ternary operator in razor (specifically on HTML attributes)? 2010-11-03

    With the WebForms view engine, I'll commonly use the ternary operator for very simple conditionals, especially within HTML attributes. For example: <a class="<%=User.Identity.IsAuthenticated ? "auth" : "anon" %>">My link here</a> Th

  • Disadvantages of using ternary operator 2010-11-10

    I have the following statments in my source code int tableField1; int tableField2; int propertyField1; int propertyField2; if (tableField1 != null) { propertyField1 = tableField1; } if (tableField2 != null) { propertyField2 = tableField1; } // the ab

  • VB.NET - Nullable DateTime and Ternary Operator 2010-11-15

    I'm having problems with a Nullable DateTime in VB.NET (VS 2010). Method 1 If String.IsNullOrEmpty(LastCalibrationDateTextBox.Text) Then gauge.LastCalibrationDate = Nothing Else gauge.LastCalibrationDate = DateTime.Parse(LastCalibrationDateTextBox.Te

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.139 (s). 11 q(s)