Direct casting vs 'as' operator in C#: when to use what?
Hello, colleagues! I'm a beginner C# developer and I've encountered a situation I don't understand. Often in code I see two ways to convert an object to a specific type: direct casting in parentheses and the 'as' operator. For example:\n\n
object obj = "Hello, world!";\nstring str1 = (string)obj; // Direct casting\nstring str2 = obj as string; // 'as' operator\n\n\nBoth options seem to work the same way, but I feel there are important differences between them. My question: what is the difference between these approaches? When is it safer to use direct casting, and when the 'as' operator? I've heard that 'as' doesn't throw an exception, but what happens then if the cast is not possible? And what about value types, like int or double? Can 'as' be used for them? I would be grateful for No answers yet.
Log in to leave an answer