Reputation: 10648
I have an array of objects:
object[] myArray
This array can contain int, string, DateTime data types and so on.
Now I am trying to check if an object within myArray is of type DateTime and not null so I perform below ternary:
string strDate = myArray[pos] != null && myArray[pos].GetType() is typeof(DateTime) ? Convert.ToDateTime(myArray[pos]).ToString("dd/MM/yyyy") : string.Empty;
But I get below error starting from typeof(DateTime):
Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
Upvotes: 3
Views: 10521
Reputation: 16049
You can use is
operator like
Solution with C#7 pattern matching feature
string strDate = (myArray[pos] is DateTime date) ? date.ToString("dd/MM/yyyy"): string.Empty;
Upvotes: 7
Reputation: 23898
The below approach will work on old C# compilers. I'd strongly suggest moving to VS 2019 though. Your life will become much easier...
var bob = myArray[pos] as DateTime?;
string strDate = bob == null ? string.Empty : bob.Value.ToString("dd/MM/yyyy");
Upvotes: 1
Reputation: 62472
You don't need to call to Convert.ToDateTime
as you've already done a check to ensure that the object is a DateTime
. Also, instead of using the ternary operator you can use the new switch
expression along with some pattern matching:
string stDate = myArray[pos] switch
{
DateTime d => d.ToString("dd/MM/yyyy"),
_ => string.Empty
};
Upvotes: 1