Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

object to struct with as operator

Why does the first one work but not the second one? Is there anything to worry about, when converting objects to structs?

struct Hex { /* ... */ }
object actionData = GetData();

1:

bool isHex = actionData is Hex;
Hex hexx = (Hex)actionData;

2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Hex hex = actionData as Hex;

>Solution :

Because as operator returns null if type check fails:

The expression of the form E as T
where E is an expression that returns a value and T is the name of a type or a type parameter, produces the same result as: E is T ? (T)(E) : (T)null except that E is only evaluated once.

Which can’t be done if T is non-nullable value type (so compiler emits the error). Using nullable value type as T will work:

object actionData = new Hex(); // your code returning boxed Hex
Hex? hex = actionData as Hex?;
if(hex.HasValue)
{
   ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading