Casting works but can't convert whats the difference and why - c#

Have the following code which works fine.
MyType convertedItem = (MyType)item;
However I get a compiler error from
var convertedItem = item as MyType;
Cannot convert type 'OtherType' to 'MyType' via a reference
conversion, boxing conversion, unboxing conversion, wrapping
conversion, or null type conversion.
Can anyone explain why \ when this occurs. An explicit cast works fine but AS wont even compile.
** How do I get 'AS' functionality in this situation. Namely I need to do a trycast and would prefer not to invoke the exceptionhandler to accomplish it. **

as doesn't work with anything that is a struct. Logically we can understand this because a struct is non nullable by default. The suggestions of casting to object work by cheating and boxing the struct

For example, the following types would give CS0039:
class MyType
{
}
class MyOtherType
{
}
MyOtherType item = new MyOtherType();
var convertedItem = item as MyType;
In the above example, the compiler has determined that given the types participating in the cast, it's impossible to perform the requested conversion.
Here providing conversion operators would solve the problem.
EDIT: working around this error with casting to Object is not recommended, as it defeats the purpose of the type system

Related

How to make sure the explicit operator throws the exception when converting null? (not nullable)

I have an explicit operator on the class MyVO, which should be non-nullable.
public class MyVO : ValueObject<MyVO>
{
public string Value { get; } // Should never be null
private MyVO(string v) => Value = v;
public static explicit operator MyVO(string vo)
{
if (string.IsNullOrWhiteSpace(vo)) throw new Exception('...');
return new MyVO(vo);
}
However, (MyVO)null will not raise an exception. The body of the method will not be run.
var myVO = (MyVO)null; // myVO will have the null value
How to make sure it's not null?
How to make sure it's not null?
By "it" I assume you mean "the result of the cast from null to MyVO". If that is not what you mean, please clarify the question.
You cannot.
An important rule of C# is a user-defined conversion never "wins" when it conflicts with a built-in conversion. It is legal to convert null to any class type, and so a cast of MyVO on the expression null will always result in a null reference. The compiler does not even consider the user-defined conversions if a built-in conversion works. (Believe me; I wrote that code!)
As D Stanley's answer correctly points out, if the null is the value of any expression of type string then the user-defined conversion is called; there is no built-in conversion from string to MyVO so the compiler looks for an applicable user-defined conversion and finds one.
Since it hurts when you do what you're doing, you should probably stop doing what you are doing. An explicit conversion is probably not the right way to implement the desired behaviour.
I guess my question should be how to make MyVO not nullable.
Upgrade to C# 8. C# 8 supports non-nullable annotations on reference types.
Note that the non-nullable annotation should be properly thought of as an annotation. The type system does not guarantee that the value of a variable annotated with a non-nullable annotation will never be observed to be null. Rather, it does its best to warn you when the code looks like it is wrong.
While we are looking at your code, I notice that you are using ValueObject<T>, which I assume you have obtained from something like
https://enterprisecraftsmanship.com/posts/value-object-better-implementation/
Let me take this opportunity to caution you that there are pitfalls to using this pattern; the constraint that you think or want to be applied to T is not the constraint that is applied to T. We often see things like this:
abstract class V<T> where T : V<T>
{
public void M(T t) { ... } // M must take an instance of its own type
}
If we have class Banana : V<Banana> then Banana.M takes as its argument a Banana, which is what we want. But now suppose we have class Giraffe : V<Banana>. In this scenario, Giraffe.M does not take a giraffe; it takes a banana, even though Giraffe has no relationship with Banana at all.
The constraint does not mean that M always takes an instance of its own class. If you are trying to construct a generic type with this kind of constraint in C#, you cannot; the C# type system is not rich enough to express that constraint.
null can be implicitly converted to any reference type, so the compiler is not using your explicit cast operator. try
string s = null;
o = (MyVO)s;
or just inline it
o = (MyVO)((string)s);

C# dynamic conversion through cast operator

I have some code that I have no control of. This code accepts an object parameter and attempts to cast it to a type known at compile time like this:
KnownType item = (KnownType) parameter;
Is it possible in C# to design a custom class MyClass (not derived from KnownType) that can be passed as parameter to the above code and be converted to KnownType by the above code, provided that MyClass can convert itself to KnownType using its member method:
protected KnownType ConvertToKnownType()
{
// conversion code goes here
}
I have tried to implement a custom conversion operator like this:
public static implicit operator KnownType(MyClass source)
{
KnownType result;
// conversion goes here
return result;
}
but it didn't work (it was not used). Am I right to assume that the cast operator only works when the source type, target type and conversion operators are known at compile time?
Edit:
I initially didn't provide more details about the code doing the conversion because I think it is irrelevant and because I am mainly interested in the way the cast operator is implemented, i.e. does it take look at the runtime type to find an appropriate converter or is the decision made at compile time?
To clear things out, KnownType is in fact DataRowView, while MyClass is a wrapper class for DataRowView that has to derive from some other type. MyClass keeps a reference to a DataRowView. Instead of binding ComboBox.DataSource to a DataView, I bind it to an IList<MyClass> but I still need the ComboBox to be able to access the DataRowView column values as if I was binding an IList<DataRowView>. Unfortunately the cast operator works the way I was afraid it would: it only takes into account compile time type information to do conversions (it does however use runtime type information when casting between types in the same inheritance tree).
No, it is not possible. The cast provided would only succeed if you're able to derive your class from that class. Any type of conversion not based on inheritance would require the class performing the conversion to do something different than what it's doing.
Am I right to assume that the cast operator only works when the source type, target type and conversion operators are known at compile time?
Yes.

Why do covariant implicit casts ignore generic constraints?

static IEnumerable<U> DoSomething<T, U>(IEnumerable<T> a)
where T : U
{
// Works, compiler can compile-time statically cast
// T as U.
T testA = default(T);
U testB = testA;
// And the following works, though:
IEnumerable<string> test2A = null;
IEnumerable<object> test2B = test2A;
// Doesn’t work. Compiler cannot compile-time statically
// cast IEnumerable<T> to IEnumerable<U> even though it is
// out and T is U.
return a;
}
I have code where being able to perform this type of implicit cast would save me writing a lot of boilerplate interface implementation code.
This seems to be the sort of thing which covariance was supposed to help with.
But I always get this error on the return a; line above:
error CS0266: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<T>' to 'System.Collections.Generic.IEnumerable<U>'. An explicit conversion exists (are you missing a cast?)
Why is this this way and is there a way to work around this without doing something like return from o in a select o;?
When messing around with my minimal repro and reading similar, but unrelated, question about interface casting, I realized that the following compiles:
static IEnumerable<U> DoSomethingElse<T, U>(IEnumerable<T> a)
where T : class, U
{
// Works! Ridik!
return a;
}
And also that the following fails with the same error message:
static void Blah()
{
// Fails for I bet the same reason that DoSomething{T, U} fails:
IEnumerable<int> a = null;
IEnumerable<object> b = a;
}
error CS0266: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'System.Collections.Generic.IEnumerable<object>'. An explicit conversion exists (are you missing a cast?)
So this seems to be related to how .net restricts certain types of assignments to reference types because boxing in these situations would either be the wrong thing (e.g., you might assume reference types and actually be working on a copy of a value type) or very hard/impossible to implement in the runtime (given an IEnumerable<int> you’d have to implement a wrapping adapting class. OK, so that sounds like something .net can’t/shouldn’t try to do for you at runtime). I think of it as a situation where .net allows pointer-style polymorphism which, by its very nature, is incompatible with the concept of value types.
So, for my case, I don’t need to support value types in my API here and adding the class constraint makes everything magical!

Which is the best practice in C# for type casting? [duplicate]

This question already has answers here:
Direct casting vs 'as' operator?
(16 answers)
Difference between is and as keyword
(13 answers)
Closed 7 years ago.
Which method is best practice to type casting and checking ?
Employee e = o as Employee;
if(e != null)
{
//DO stuff
}
OR
if(o is Employee)
{
Employee e = (Employee) o;
//DO stuff
}
At least there are two possibilities for casting, one for type checking and a combination of both called pattern matching. Each has its own purpose and it depends on the situation:
Hard cast
var myObject = (MyType)source;
You normally do that if you are absolutely sure if the given object is of that type. A situation where you use it, if you subscribed to an event handler and you cast the sender object to the correct type to work on that.
private void OnButtonClick(object sender, EventArgs e)
{
var button = (Button)sender;
button.Text = "Disabled";
button.Enabled = false;
}
Soft cast
var myObject = source as MyType;
if (myObject != null)
// Do Something
This will normally be used if you can't know if you really got this kind of type. So simply try to cast it and if it is not possible, simply give a null back. A common example would be if you have to do something only if some interface is fullfilled:
var disposable = source as IDisposable;
if(disposable != null)
disposable.Dispose();
Also the as operator can't be used on a struct. This is simply because the operator wants to return a null in case the cast fails and a struct can never be null.
Type check
var isMyType = source is MyType;
This is rarely correctly used. This type check is only useful if you only need to know if something is of a specific type, but you don't have to use that object.
if(source is MyType)
DoSomething();
else
DoSomethingElse();
Pattern matching
if (source is MyType myType)
DoSomething(myType);
Pattern matching is the latest feature within the dotnet framework that is relevant to casts. But you can also handle more complicated cases by using the switch statement and the when clause:
switch (source)
{
case SpecialType s when s.SpecialValue > 5
DoSomething(s);
case AnotherType a when a.Foo == "Hello"
SomethingElse(a);
}
I think this is a good question, that deserves a serious and detailed answer. Type casts is C# are a lot of different things actually.
Unlike C#, languages like C++ are very strict about these, so I'll use the naming there as reference. I always think it's best to understand how things work, so I'll break it all down here for you with the details. Here goes:
Dynamic casts and static casts
C# has value types and reference types. Reference types always follow an inheritance chain, starting with Object.
Basically if you do (Foo)myObject, you're actually doing a dynamic cast, and if you're doing (object)myFoo (or simply object o = myFoo) you're doing a static cast.
A dynamic cast requires you to do a type check, that is, the runtime will check if the object you are casting to will be of the type. After all, you're casting down the inheritance tree, so you might as well cast to something else completely. If this is the case, you'll end up with an InvalidCastException. Because of this, dynamic casts require runtime type information (e.g. it requires the runtime to know what object has what type).
A static cast doesn't require a type check. In this case we're casting up in the inheritance tree, so we already know that the type cast will succeed. No exception will be thrown, ever.
Value type casts are a special type of cast that converts different value types (f.ex. from float to int). I'll get into that later.
As, is, cast
In IL, the only things that are supported are castclass (cast) and isinst (as). The is operator is implemented as a as with a null check, and is nothing more than a convenient shorthand notation for the combination of them both. In C#, you could write is as: (myObject as MyFoo) != null.
as simply checks if an object is of a specific type and returns null if it's not. For the static cast case, we can determine this compile-time, for the dynamic cast case we have to check this at runtime.
(...) casts again check if the type is correct, and throw an exception if it's not. It's basically the same as as, but with a throw instead of a null result. This might make you wonder why as is not implemented as an exception handler -- well, that's probably because exceptions are relatively slow.
Boxing
A special type of cast happens when you box a value type into an object. What basically happens is that the .NET runtime copies your value type on the heap (with some type information) and returns the address as a reference type. In other words: it converts a value type to a reference type.
This happens when you have code like this:
int n = 5;
object o = n; // boxes n
int m = (int)o; // unboxes o
Unboxing requires you to specify a type. During the unboxing operation, the type is checked (like the dynamic cast case, but it's much simpler because the inheritance chain of a value type is trivial) and if the type matches, the value is copied back on the stack.
You might expect value type casts to be implicit for boxing -- well, because of the above they're not. The only unboxing operation that's allowed, is the unboxing to the exact value type. In other words:
sbyte m2 = (sbyte)o; // throws an error
Value type casts
If you're casting a float to an int, you're basically converting the value. For the basic types (IntPtr, (u)int 8/16/32/64, float, double) these conversions are pre-defined in IL as conv_* instructions, which are the equivalent of bit casts (int8 -> int16), truncation (int16 -> int8), and conversion (float -> int32).
There are some funny things going on here by the ways. The runtime seems to work on multitudes of 32-bit values on the stack, so you need conversions even on places where you wouldn't expect them. For example, consider:
sbyte sum = (sbyte)(sbyte1 + sbyte2); // requires a cast. Return type is int32!
int sum = int1 + int2; // no cast required, return type is int32.
Sign extension might be tricky to wrap your head around. Computers store signed integer values as 1-complements. In hex notation, int8, this means that the value -1 is 0xFF. So what happens if we cast it to an int32? Again, the 1-complement value of -1 is 0xFFFFFFFF - so we need to propagate the most significant bit to the rest of 'added' bits. If we're doing unsigned extensions, we need to propagate zero's.
To illustrate this point, here's a simple test case:
byte b1 = 0xFF;
sbyte b2 = (sbyte)b1;
Console.WriteLine((int)b1);
Console.WriteLine((int)b2);
Console.ReadLine();
The first cast to int is here zero extended, the second cast to int is sign extended. You also might want to play with the "x8" format string to get the hex output.
For the exact difference between bit casts, truncation and conversion, I refer to the LLVM documentation that explains the differences. Look for sext/zext/bitcast/fptosi and all the variants.
Implicit type conversion
One other category remains, and that's the conversion operators. MSDN details how you can overload the conversion operators. Basically what you can do is implement your own conversion, by overloading an operator. If you want the user to explicitly specify that you intend to cast, you add the explicit keyword; if you want implicit conversions to happen automagically, you add implicit. Basically you'll get:
public static implicit operator byte(Digit d) // implicit digit to byte conversion operator
{
return d.value; // implicit conversion
}
... after which you can do stuff like
Digit d = new Digit(123);
byte b = d;
Best practices
First off, understand the differences, which means implementing small test programs until you understand the distinction between all of the above. There's no surrogate for understanding How Stuff Works.
Then, I'd stick to these practices:
The shorthands are there for a reason. Use the notation that's the shortest, it's probably the best one.
Don't use casts for static casts; only use casts for dynamic casts.
Only use boxing if you need it. The details of this go well beyond this answer; basically what I'm saying is: use the correct type, don't wrap everything.
Notice compiler warnings about implicit conversions (f.ex. unsigned/signed) and always resolve them with explicit casts. You don't want to get surprises with strange values due to sign/zero extension.
In my opinion, unless you know exactly what you're doing, it's best to simply avoid the implicit/explicit conversion -- a simple method call is usually better. The reason for this is that you might end up with an exception on the loose, that you didn't see coming.
With the second method, if the cast fails an exception is thrown.
When casting using as, you can only use reference types. so if you are typecasting to a value type, you must still use int e = (int) o; method.
a good rule of thumb, is : if you can assign null as a value to the object, you can type cast using as.
that said, null comparison is faster than throwing and catching an exception, so in most cases, using as should be faster.
I can't honestly say with certainty if this applies with your is check in place though. It could fail under some multi threading conditions where another thread changes the object you're casting.
I would use the as (safe-cast) operator if I need to use the object after casting. Then I check for null and work with the instance. This method is more efficient than is + explicit cast
In general, the as operator is more efficient because it actually returns the cast value if the cast can be made successfully. The is operator returns only a Boolean value. It can therefore be used when you just want to determine an object's type but do not have to actually cast it.
(more information here).
I am not sure about it but I think that is is using as under the hood and just returns if the object after casting is null (in case of reference types) / an exception was thrown (in case of value types) or not.
Well, it's a matter of taste and specifics of problem that you're dealing with. Let's have a look at two examples with generic methods.
For generic method with 'class' constraint (the safest approach with double cast):
public void MyMethod<T>(T myParameter) where T : class
{
if(myParameter is Employee)
{
// we can use 'as' operator because T is class
Employee e = myParameter as Employee;
//DO stuff
}
}
Also you can do someting like this (one cast operation here but defined variable of type that may or may not be correct) :
public void MyMethod<T>(T myParameter) where T : class
{
Employee e;
if((e = myParameter as Employee) != null)
{
//DO stuff with e
}
}
For generic method with 'struct' constraint :
public void MyMethod<T>(T myParameter) where T : struct
{
if(myParameter is int)
{
// we cant use 'as' operator here because ValueType cannot be null
// explicit conversion doesn't work either because T could be anything so :
int e = Convert.ToInt32(myParameter);
//DO stuff
}
}
Simple scenario with explicit cast:
int i = 5;
object o = (object)i; // boxing
int i2 = (int)o; // unboxing
We can use explicit cast here because we are 100% sure of what types do we use.

What is the difference between casting and using "as" in C#?

If there is a difference, what is the difference between the two ways of doing the following cast?
In this case e is a GridViewRowEventArgs object.
GridView gv = (GridView)e.Row.FindControl("gv"); //first way
GridView gv2 = e.Row.FindControl("gv") as GridView; //second way
The differences are:
If a cast fails, it throws an InvalidCastException.
If the as operator fails, it just returns a null reference.
You can't use as with non-nullable value types (e.g. you can't do "o as int").
The cast operator is also used for unboxing. (as can be used to unbox to a nullable value type.)
The cast operator can also perform user-defined conversions.
EDIT: I've written elsewhere about when I feel it's appropriate to use which operator. That might be worth a read...
What isn't mentioned in the above answers is intent -- why are you performing the conversion, and (more importantly) what happens on the lines after the conversion?
For example, I've seen code similar to the following a number of times:
if ((foo as SomeType).SomeMethod()) { /* ... */ }
This could be compared to the cast-using version:
if (((SomeType) foo).SomeMethod()) { /* ... */ }
So, which of these is better?
The cast is.
Using as will result in a NullReferenceException if the conversion fails.
Using a cast will result in an InvalidCastException if the conversion fails.
Now tell me, which is a more useful exception for debugging? A NullReferenceException, which could be produced by nearly anything, or an InvalidCastException, which lets you know what actually went wrong?
Thus, only use as if the conversion is actually optional (meaning that there must be a null check before using the variable). Otherwise, use a cast, thus making your intentions more explicit.
The safe cast as
variable as type
does the same as
(variable is type) ? (type)variable : (type)null
and will not work for value types.
In general, the difference between a static cast and "as", is that the cast will throw an Exception if it fails, whereas "as" will just set the variable to null.
The "as" statement basically makes an attempt to cast the variable, and returns null if it fails rather than throwing an exception. As such, the value to which you're casting must be nullable - a reference type or a nullable primitive. In your example, you'd have to do:
int? i2 = o as int;
or it won't compile.
If you however used a reference type say Table the first one would raise InvalidCastException in case o was not assignable to Table and the second would just return null.
Apart from the issue which Jon pointed out, the as keyword effectively casts o as SomeClass. If o isn't derived from SomeClass it returns null. Whereas a simple cast would throw an exception.
SomeClass i2 = o as SomeClass;
becomes
SomeClass i2;
if (o is SomeClass)
i2 = (SomeClass)o;
else
i2 = null;
I might be stating the obvious here, but one thing that you get with the 'as' cast is, that you are guaranteed to end up with an object of the type you requested.
This comes in handy in certain situations.

Categories

Resources