This question already has answers here:
Direct casting vs 'as' operator?
(16 answers)
Closed 9 years ago.
I just ran across another way to cast objects in C#. I have always used (CastType)variable. I just noticed some code using variable as CastType. The latter reminds me of VB.
Is there a difference between the two methods of casting other than syntax?
The first one will throw InvalidCastException if the types don't match (refer to the documentation - "Explicit conversions" section). The second one (the as operator) will produce null value instead.
Related
This question already has answers here:
Why C# 6.0 doesn't let to set properties of a non-null nullable struct when using Null propagation operator?
(2 answers)
Why some types do not have literal modifiers
(6 answers)
Closed 2 years ago.
I just noticed that property assignment is not allowed in combination with the null conditional operator.
With methods is it not a problem at all though.
I always thought that properties are just syntactic sugar for setter methods.
item?.SetMarker(Marker.Start); // Perfectly fine
item?.Marker = Marker.Start; // Error CS0131 The left-hand side of an assignment must be a variable, property or indexer
So why is one allowed and the other not?
I'm pretty sure there is a good theoretical reason.
With the small hope of getting smarter I just try to know why :)
PS - I noticed the same behaviour in TypeScript.
In the second line, when item is null, it does not have any Marker, so you are not able to assign any value to it.
On the other hand, In the first line, when item is null, SetMarker method is not even called and in another word you do not try to assign anything.
This question already has answers here:
Is this pattern matching expression equivalent to not null
(2 answers)
Closed 2 years ago.
So, I think in the current C# version which is C# 8. There are a few ways to check the reference types are not null. I am confused by these two below:
o is object
o is {}
What's the main difference between them, I cannot find much info for them.
Can someone explain it to me? Which one is recommended? Or what are the pro and cons of each one?
o is object is the original way of checking the type of an instance (available since C# 1.0)
o is {} uses the pattern matching with property patterns introduced in C# 8.0
{} denotes an object instance with any (or none) properties, i.e. any object instance.
This question already has answers here:
Get the type name
(10 answers)
Closed 2 years ago.
I have an enumerable as follows:
IEnumerable<SomeObjectType> dataToImport;
At runtime I run the following code:
dataToImport.GetType().ToString()
So far so good. Checking results at runtime shows me something like the following :
System.Collections.Generic.List`1[SomeObjectType]
Can somebody tell me what that `1 means and where it is coming from? Should I expect this on all collections?
It's a placeholder for the first generic type argument. You should expect it on anything with a generic type.
The backtick(`) followed by a digit represent the number of generic arguments. For example List<T> has one generic argument hence `1
This question already has answers here:
What is the purpose of a question mark after a value type (for example: int? myVariable)?
(9 answers)
Closed 7 years ago.
I have the following enigmatic declaration in C#:
Dictionary<string, DateTime?> badCameras = new Dictionary<string, DateTime?>();
This was written by a programmer no longer here & IS compiling! What ever does the '?' mean following DateTime object? Has it something to do with a struct? I've searched online & am finding nothing? BTW, this is .NET3.5.
Thanks
DateTime? is compiler sugar for Nullable<DateTime>. Effectively, nullable types allow for the use of null when dealing with value types that don't normally support null. See here for details.
The ? in that context is a shortcut for Nullable<T>. In your example, its equivalant to:
Dictionary<string, Nullable<DateTime>>
The main purpose is to allow value types to hold the null value.
This question already has answers here:
Direct casting vs 'as' operator?
(16 answers)
Casting vs using the 'as' keyword in the CLR
(18 answers)
Closed 8 years ago.
This could be a trivial question, I've seen several different variations of Cast.
What is the difference?
Is one better than another (Performance)?
Is it just a matter of preference, code legibility?
Example One:
command.ExecuteScalar() as string;
Example Two:
(string)command.ExecuteScalar();
Both will impact the ExecuteScalar() differently, so the question is when interacting with the database is one more ideal than another?
The first ( command.ExecuteScalar() as string; )will do a runtime attempt to convert the result of ExecuteScalar() into a string. If the resulting type is not a string, you will receive null. The as keyword also only performs reference conversions, nullable conversions, and boxing conversions, so you can't use it directly with non nullable value types.
The second ( (string)command.ExecuteScalar(); ) will do a conversion to string directly, and raise an InvalidCastException if the resulting value is not a string.
Is one better than another (Performance)?
In general, using the second option should provide (insignificantly) better performance if you know the result is always going to be a string.
Is it just a matter of preference, code legibility?
This is where I make the stronger differentiation. Using as suggests that the result may not be a string, and you will be handling the null check. Using a direct cast suggests that you know it's always a string, and anything else is an error and should raise an exception.
In my opinion, this should be the deciding factor for which to choose, since it shows your intent directly in the code.
(string)command.ExecuteScalar() will throw an exception if command.ExecuteScalar() cannot be cast.
command.ExecuteScalar() as string will just return null instead.